servicestack,ormlite-servicestack , Access ServiceStack session from ConnectionFilter


Access ServiceStack session from ConnectionFilter

Question:

Tag: servicestack,ormlite-servicestack

I am using SQL Server and database triggers to keep a data-level audit of all changes to the system. This audit includes the userID / name of whomever initiated a change. Ideally I'd like to do something like this in my AppHost.Configure method:

SqlServerDialect.Provider.UseUnicode = true;
var dbFactory = new OrmLiteConnectionFactory(ConnectionString, SqlServerDialect.Provider)
        {
            ConnectionFilter = (db =>
            {
                IAuthSession session = this.Request.GetSession();
                if (session != null && !session.UserName.IsNullOrEmpty())
                {
                    System.Data.IDbCommand cmd = db.CreateCommand();
                    cmd.CommandText = "declare @ci varbinary(128); select @ci = CAST(@Username as varbinary(128)); set context_info @ci";
                    System.Data.IDbDataParameter param = cmd.CreateParameter();
                    param.ParameterName = "Username";
                    param.DbType = System.Data.DbType.String;
                    //param.Value = session.UserName;
                    param.Value = session.UserAuthId;
                    cmd.Parameters.Add(param);
                    cmd.ExecuteNonQuery();
                }

                return new ProfiledDbConnection(db, Profiler.Current);
            }),
            AutoDisposeConnection = true
        };
        container.Register<IDbConnectionFactory>(dbFactory);

Of course, this doesn't work because this.Request doesn't exist. Is there any way to access the current session from the ConnectionFilter or ExecFilter on an OrmLite connection?

The other approach I had started, doing an override of the Db property of Service, doesn't work any more because I've abstracted some activities into their own interfaced implementations to allow for mocks during testing. Each of these is passed a function that is expected to return the a DB connection. Example:

// Transaction processor
container.Register<ITransactionProcessor>(new MockTransactionProcessor(() => dbFactory.OpenDbConnection()));

So, how can I ensure that any DML executed has the (admittedly database-specific) context information needed for my database audit triggers?


Answer:

The earlier multi tenant ServiceStack example shows how you can use the Request Context to store per-request items, e.g. you can populate the Request Context from a Global Request filter:

GlobalRequestFilters.Add((req, res, dto) =>
{
    var session = req.GetSession();
    if (session != null)
        RequestContext.Instance.Items.Add(
            "UserName", session.UserName);
});

And access it within your Connection Filter:

ConnectionFilter = (db =>
{
    var userName = RequestContext.Instance.Items["UserName"] as string;
    if (!userName.IsNullOrEmpty()) {
       //...
    }
}),

Related:


ServiceStack intercept requests before they are sent client side


servicestack
I have implemented a custom HMAC authentication for servicestack (example shown here). As suggested at the bottom of the link, I wanted to do something like this client side: var client = new JsonServiceClient(); client.LocalHttpWebRequestFilter += delegate(HttpWebRequest request) { // ContentType still null at this point so we must hard...

Can I check for the existence of an HTTP only cookie with Javascript? [duplicate]


javascript,authentication,cookies,servicestack,single-page-application
This question already has an answer here: Check if httponly cookie exists in Javascript 1 answer Can I use Javascript to see if an HTTP-only cookie exists, I don't want to see the value, just know whether or not it is there. I need this because I have an...

ServiceStack Cannot Set Session with Redis


servicestack,servicestack.redis
I am using the AuthFeature to authenticate my user. I am experience an issue writing to Redis. Has anyone experienced this before? Using ServiceStack 4.0.40 and Redis-64 v2.8.19 installed by Choco // Register the caching container.Register<IRedisClientsManager>(c => new RedisManagerPool(ConfigUtils.GetAppSetting("RedisHost"))); // Host: 127.0.0.1 container.Register<ICacheClient>(c => c.Resolve<IRedisClientsManager>().GetCacheClient()); Response: { "userId": null, "sessionId":...

ServiceStack.Text deserialize string into single object null reference


c#,.net,json,servicestack
I have the following code. With JSON.NET it works fine where I can deserialize the string into the CustomMaker object. With ServiceStack.Text I get null. I've tried doing { get; set; } and removing and adding the constructor. With JSON.NET it simply worked like JsonConvert.DeserializeObject(xString); Any idea why this does...

ServiceStack authentication with both [Authenticate] and [ValidateApiKey] attributes


authentication,servicestack,api-key
I have some endpoints decorated with the [Authenticate] attribute. Now a third party client has to access the same endpoint by using a shared API key. As the code would be exactly the same for the two cases, I would like to check first if the current request comes from...

ServiceStack CredentialsAuthProvider is ignore rememberMe = false


servicestack
I am using CredentialsAuthProvider with SS v4.0.39, and have been for well over a year. A client has asked what the "remember me" checkbox on the login page does. My understanding was that this determines whether the user's session is persisted across browser tabs. However, having tested it, when rememberMe...

ServiceStack MemoryCached Authentication Register User


c#,servicestack
I'm creating user service. Right now there can't be a normal repository system involved. I try to implement a authentication module for a single page app. Before i've written simply a mockup. The customer likes to see the default Auth Provider. Right now only a login service like /auth/credentials is...

ServiceStack minimum configuration to get Redis Pub/Sub working between multiple Web sites/services


servicestack,servicestack.redis
Let's say for sake of argument I have 3 web service hosts running, and only one of them has registered any handlers (which I think equates to subscribing to the channel/topic) e.g. var mqService = new RedisMqServer(container.Resolve<IRedisClientsManager>()) { DisablePriorityQueues = true }; container.Register<IMessageService>(mqService); container.Register(mqService.MessageFactory); mqService.RegisterHandler<OutboundInitiateCallInfo>(ServiceController.ExecuteMessage);...

OrmLite: SQLiteExceptionSQL logic error or missing database near “)”: syntax error


c#,sqlite,servicestack,ormlite-servicestack
Hi i'm trying to test out if I delete a parent object, the child will automatically be deleted too using OrmLite and the in-memory database Sqlite this is my test code but it throws me System.Data.SQLite.SQLiteExceptionSQL logic error or missing database near ")": syntax error at the db.Save() line. What...

How do I enable HTTP Compression when using servicestack with IIS8


compression,servicestack
I had a project that built on the latest version of servicestack 4. And it seems the response will always not including content-coding:gzip whatever I tried. I've already enabled the dynamic compression on the IIS. Don't know what else to do. Do I need to add something to my coding?...

ServiceStack Self Hosting Redirect any 404 for SPA (Url Rewrite)


angularjs,servicestack
I'm using self hosting servicestack for a single page application with mvc and razor. On the same apphost i serve some api. The problem is i need some a 404 redirect to the main path "/" to get html5 mode running in AngularJS. I've tried: DefaultRedirectPath = "/" this.GlobalHtmlErrorHttpHandler =...

How to make ServiceStak service internal access only


.net,servicestack
I Want to make all services access internal only. Is there any way to global set RestrictAttribute to affect all services ?

ServiceStack Soap 1.2 HTTPS Client


c#,soap,https,servicestack,soap1.2
I have a ServiceStack based Soap Client, which operates correctly for HTTP but when I try to use HTTPS it gives me this error ServiceStack.WebServiceException: The provided URI scheme 'https' is invalid; ex pected 'http'. Parameter name: via ---> System.ArgumentException: The provided URI scheme 'http s' is invalid; expected 'http'....

Ormlite int based enums coming as varchar(max)


servicestack,ormlite-servicestack
Can anyone tell me how to correctly get ORMLite to store enums as integers? I know that this was not supported in 2012 but i found code for some unit tests that suggest it should work now but it doesn't. When we try the column gets created as a varchar(max)...

How to do a GroupBy statement with ServiceStack OrmLite


ormlite-servicestack
I am doing some queries for Data Visualization and rely on GroupBy, Avg, Sum, and similar functions to get a good dataset from the DB. I would like to use something similar to GroupBy with ServiceStack OrmLite. On the ShippersExample page I see the following query. Is there an easier...

Servicestack Authentication namespace using SOAP


.net,api,soap,servicestack
I'm getting this error when using SOAPUI to send an authenticate request to my ServiceStack API. Expecting element 'Authenticate' from namespace 'http://schemas.servicestack.net/types'.. Encountered 'Element' &nbsp;with name 'Authenticate', namespace 'http://correctnamespace.com/schemas/2015/05/MyAPI/' Here's my apphost setup: SetConfig(new HostConfig { HandlerFactoryPath = "api", DefaultContentType = "application/json", WsdlServiceNamespace = "http://correctnamespace.com/schemas/2015/05/MyAPI/", DebugMode = false, UseHttpsLinks =...

How to prevent the logging of a failed request to favorite.ico with ServiceStack


servicestack
This will be the 5th such question that centers around the favorite.ico and ServiceStack webservice framework. I understand the rationale behind logging resource not found, and most of the workarounds use the built-in not found handler e.g. appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => { if (pathInfo.StartsWith("favicon")) return new NotFoundHttpHandler(); }); but this...

ServiceStack Is IsDebuggingEnabled in View (HttpContext missing)


asp.net-mvc,servicestack
I'm using ServiceStack. In my layout view i need to know for an condition if the application is debugging or not. For some reason there is no HttpContext. I've tried to install Install-Package Microsoft.AspNet.Mvc. Than Install-Package Install-Package ServiceStack.Mvc. Now i can download localhost but there is no website visible after...

Servicestack reverse routing exception


servicestack
I'm trying to get the absolute url out of a ServicesSatck service but I'm receiving the following exception: None of the given rest routes matches 'SingleUser' request: /user/UserName/{UserName}: Allowed HTTP methods 'Get' does not support the specified 'GET' method. SingleUser class has the following routes declared as metadata : [Route("/user",...

ServiceStack V4 Basic Auth with wrong credentials + CORS


c#,.net,servicestack,cors
I was trying to enable CORS for ServiceStack V4 project. My plugin configuration is as follows: Plugins.Add(new CorsFeature(allowedHeaders:"Content-Type, Authorization")); I also use HTTP basic auth for authentication: Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider(), //Sign-in with Basic Auth new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials }));...

Servicestack Embedding Javascript Resources


razor,servicestack,mef
I have been working on an MEF/Servicestack based framework for an SaaS product. I am compiling razor views into external modules that are loaded during runtime with MEF. I am struggling trying to embed javascript resources into the dlls and then referencing them successfully when the view is loaded. Has...

How could I add a delay in processing failed messages in ServiceStack Redis MQ


servicestack,mq,servicestack.redis,redismqserver
Is there an easy way to get Servicestack to wait x seconds before retrying a failed MQ item (using Redis MQ). At the moment it just tries 3 times consecutively with no delay.

Convert SQL to ServiceStack.ORMLite Sql Server


c#,sql-server,tsql,servicestack,ormlite-servicestack
How to convert the following SQL to ServiceStack.OrmLite Sql Server format? /* Total Receipts */ select convert(date, t.TransactionDate) [Date], tm.TeamId,a.AccountNumber, count(distinct(t.RequisitionNumber)) Total from task.tblTransactions t inner join task.tblRequisitions r on r.RequisitionNumber = t.RequisitionNumber inner join task.tblAccounts a on a.AccountNumber = r.AccountNumber inner join Team tm on tm.DivisionId = a.DivisionId where...

ServiceStack versioning - how to customize the request deserialization based on versioning


servicestack
I am working on a new API where we have requirement for many to many versioning. Old Client -> New Server Old Server -> New client and everything in between I've read some of the other posts about defensive programming and having DTOs that evolve gracefully... and we are definitely...

Hide/remove columns from servicestack requestlogger page


servicestack
Is there a way to hide or remove columns from the request logs page (RequestLogger plugin) in ServiceStack? The Form Data and Items columns are never going to be useful for us so displaying them just wastes unnecessary screen real estate....

What happened to SafeConvertAll in ServiceStack?


servicestack
I am looking at the ServiceStack.UseCases application, specifically the ImageResizer project. The code in Global.asax references an extension method called SafeConvertAll, which does not appear to be a part of SS any longer. What happened to this function and what should I use to replace it? Thanks...

ServiceStack selfhosting disable caching for memory


model-view-controller,servicestack
Using Selfhosting standard ServiceStack MVC Application every request get cached in the memory. Changing any js file have no conscience until i restart the server. Is there any way around this problem for developing purposes?

Updating Xamarin app with servicestack


xamarin,servicestack
where is IosPclExportClient?? I used to use PclExport.Configure(new IosPclExport()); But I have no idea what happened to IosPclExport - Now I see people are using IosPclExportClient.Configure(); But IosPclExportClient isn't available?! Why does all this have to change all the time?!...

How to use InsertOnly method in OrmLite?


servicestack,ormlite,ormlite-servicestack
Following this example, how is the correspondent for the method InsertOnly? var updated = await dbCon.UpdateOnlyAsync(timesheet, onlyFields: x => new { x.LogInTime, x.LogOffTime, x.IsFlaggedByLeader, x.LeaderComment, x.IsModified }, @where: x => x.Id == timesheet.Id) > 0; I couldn't find an example on Internet and in the Ormlite documentation. ...

Soap Address Location : ServiceStack SOAP 1.2


soap,wsdl,servicestack
I've been looking around for an answer but I've found nothing that solves my problem, forgive me if this has been asked before. I've got a REST and SOAP API and my problem is that when i add my swdl into SoapUI it opens it up and points to the...

Service Stack set HttpCookie.Secure Flag / Attribute?


servicestack
I'm trying to set the Secure Flag on Session Cookies (ie https://www.owasp.org/index.php/SecureFlag). I've attempted: public override void Configure(Container container) { ... Config.OnlySendSessionCookiesSecurely = true; ... } Without success - when viewing in Fiddler, Chrome Developer Tools, etc - the Secure Flag is not being set. Any help would be appreciated....

LINQ query fails with nullable variable ormlite


linq,servicestack,ormlite-servicestack
I'm trying to write following LINQ query using ServiceStack Ormlite. dbConn.Select<Product>(p => p.IsActive.HasValue && p.IsActive.Value) Here, Product is my item class and "IsActive" is Nullable Bool property in that class. When this line executes it always throws "InvalidOperationException" with the message variable 'p' of type '' referenced from scope '',...

ServiceStack View 403 (Forbidden)


razor,servicestack,servicestack-razor
I have setup Service Stack web project with a couple of views. I can access the /Default.cshtml view without any problems but when I try to access anything in the /Views/ folder I get the below error: Forbidden Request.HttpMethod: GET Request.PathInfo: /Views/MyView.cshtml Request.QueryString: Request.RawUrl: /Views/MyView.cshtml I have looked at the...

ServiceStack not rendering Razor View, only seeing Snap Shot


twitter-bootstrap,razor,twitter-bootstrap-3,servicestack,servicestack-razor
I've set up a very basic ServiceStack project with Bootstrap and I'm trying to get it to see my homepage (Razor View) which it doesn't, so I get the Snapshot of my homepage. Here are the steps I take to create the project: Create new Project "ServiceStack ASP.Net with Bootstrap"...

Do the Request filters get run from BasicAppHost?


servicestack
I know that the services get wired-up by instantiating the BasicAppHost, and the IoC by using the ConfigureContainer property, but where is the right place to add the filters? The test in question never fire the global filter: [TestFixture] public class IntegrationTests { private readonly ServiceStackHost _appHost; public IntegrationTests() {...

How to configure NLog (Servicestack) for Multiple files


c#,servicestack,nlog
I need to save one log file for each of my threads running. So I want different log files, the code below saves one log, but I need to create diferent ones, how can I call the method saying which file I want to save? LogManager.LogFactory = new NLogFactory(); var...

ServiceStack Redis latest list by date


c#,model-view-controller,redis,servicestack
If I have a class public class Article { public int Id { get; set; } public string Title { get; set; } public string ShortDesc { get; set; } public DataTime UpateDate { get; set; } } What is the best way of getting list of users from Redis...

Swagger url for self hosted servicesteack service


.net,web-services,servicestack,swagger
I am trying to use ServiceStack.Api.Swagger and by default swagger url is pre-populated with /swagger-ui/resources While for self-hosted ServiceStack service it is available right under /resources How can I change routing for self-hosted service for embedded swagger resources or update default swagger url. Routing update is preferable way as it...

ServiceStack Authenticates both iOS Apps when one is logged in


rest,xamarin,servicestack,restful-authentication,servicestack-auth
I'm using the awesome ServiceStack to implement my REST backend which serves two iPhone apps written in Xamarin. Everything works great but i'm struggling in getting sessions to work correctly when the two apps are installed on the same device ! The issue is that if I login in one...

ServiceStack AutoQuery ordering


order,servicestack
I am using AutoQuery which makes writing services very simple. One of my queries needs to order descending by value X and then ascending by value Y. It appears that in AutoQuery you can order everything ascending or descending but not a combination. To get around this I added custom...

ServiceStack OrmLite and transactions


sql-server,transactions,ormlite-servicestack
I am trying to execute sql inside a transaction using ServiceStack OrmLite. The code below works with Sqlite but not with SqlServer. With SqlServer I get the following error: ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending local transaction....

ServiceStack.OrmLite SqlServer new Merge method doesn't work for different names of references


c#,sql-server,servicestack,ormlite-servicestack
I tried to use the new merge method in ServiceStack.OrmLite Sql Server it works perfectly to load references when the name of the column is the same as the Child Table: var result = dbCon.SqlList<TimeSheet>("EXEC getAllTimeSheets @timeSheetTypeId, @teamId, @employeeId, @fromDate, @toDate", new { timeSheetTypeId, teamId, employeeId, fromDate, toDate }); //...

How to handle JSV with a comma(,) containing value?


servicestack,servicestack-text
Assume we have a string as follows: string employeeDetails=[{Id:100,Name:John,Address:#39 ,street ,Country},{Id:101,Name:Brein,Address:#79 ,street ,Country}]; This is how i am Deserialising my string. JsvStringSerializer jsv = new JsvStringSerializer(); List<EmploymentDetails> employmentDetails = jsv.DeserializeFromString<List<EmploymentDetails>>(employeeDetails); As a result i am getting each employee address upto first comman i.e., employeeDetail.Address value as "#39" instead of "#39...

Retrieve Custom exception message from service layer in ajax call


jquery,asp.net-mvc-5,asp.net-ajax,servicestack
I have developed my application in ASP.net MVC5 using ServiceStack framework. In my app, on button click, I make ajax server call which returns data. this.LoadData = function(){ $.ajax({ url: '@Url.Action("SearchCustomer", "Customer")', cache: false, type: 'GET', contentType: 'application/json', data: { 'IndexNo': this.IndexNo }, success: function (result) { }, error: function...