WebApi Per-Request Storage for self-hosting

When hosting WebApi is IIS, you have access to the HttpContext and you can use a collection of elements to store objects for a single HTTP request.

In self-service, you no longer have an HttpContext, so what can I use to store an object for a single request?

+4
source share
2 answers

Obviously, there is no direct equivalent to System.Web HttpContext in its own host.

However, if you want to run information for a single request, each HttpRequestMessage provides a <string, object> dictionary called Properties - http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage.properties. aspx , which you can use to transfer data between handlers, filters, binders, etc.

+6
source

For selfhost (without IIS), you can build an attribute class derived from the System.Web.Http.Filters.ActionFilterAttribute type (in the assembly system.web.http.net 4.0+). Then override the OnActionExecuted method as shown below:

 public class NoResponseCachingAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response.Headers.CacheControl == null) actionExecutedContext.Response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue(); actionExecutedContext.Response.Headers.CacheControl.NoCache = true; actionExecutedContext.Response.Headers.CacheControl.NoStore = true; actionExecutedContext.Response.Headers.CacheControl.MustRevalidate = true; base.OnActionExecuted(actionExecutedContext); } } 

This approach worked for my application.

0
source

Source: https://habr.com/ru/post/1433902/


All Articles