servicestack,ormlite-servicestack , Access ServiceStack session from ConnectionFilter

Access ServiceStack session from ConnectionFilter


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;

                return new ProfiledDbConnection(db, Profiler.Current);
            AutoDisposeConnection = true

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?


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)
            "UserName", session.UserName);

And access it within your Connection Filter:

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


ServiceStack MemoryCached Authentication Register User

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...

How to do a GroupBy statement with ServiceStack OrmLite

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.Text deserialize string into single object null reference

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...

How do I enable HTTP Compression when using servicestack with IIS8

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 AutoQuery ordering

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 authentication with both [Authenticate] and [ValidateApiKey] attributes

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 intercept requests before they are sent client side

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...

Ormlite int based enums coming as varchar(max)

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 make ServiceStak service internal access only

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

Retrieve Custom exception message from service layer in ajax call

I have developed my application in 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...

LINQ query fails with nullable variable ormlite

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 Is IsDebuggingEnabled in View (HttpContext missing),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 V4 Basic Auth with wrong credentials + 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 Soap 1.2 HTTPS Client

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'....

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

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...

ServiceStack Authenticates both iOS Apps when one is logged in

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...

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

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.

Soap Address Location : ServiceStack SOAP 1.2

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...

ServiceStack not rendering Razor View, only seeing Snap Shot

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"...

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

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 }); //...

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

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...

Swagger url for self hosted servicesteack service

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 OrmLite and transactions

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....

Service Stack set HttpCookie.Secure Flag / Attribute?

I'm trying to set the Secure Flag on Session Cookies (ie 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....

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

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...

Do the Request filters get run from BasicAppHost?

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() {...

Servicestack Authentication namespace using SOAP

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

ServiceStack selfhosting disable caching for memory

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?

How to prevent the logging of a failed request to favorite.ico with 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...

What happened to SafeConvertAll in 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 reverse routing exception

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",...

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

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...

ServiceStack Cannot Set Session with 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: container.Register<ICacheClient>(c => c.Resolve<IRedisClientsManager>().GetCacheClient()); Response: { "userId": null, "sessionId":...

ServiceStack CredentialsAuthProvider is ignore rememberMe = false

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...

Updating Xamarin app with 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?!...

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

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 =...

ServiceStack View 403 (Forbidden)

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...

How to configure NLog (Servicestack) for Multiple files

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

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...

Hide/remove columns from servicestack requestlogger page

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....

Convert SQL to ServiceStack.ORMLite Sql Server

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 Embedding Javascript Resources

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 to use InsertOnly method in OrmLite?

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. ...

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

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);...