Web API action filter - equivalent to Controller.TempData?

In my System.Web.Mvc Action filters, I previously used TempData to store an instance of my unitOfWork service as follows:

public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.TempData[UnitOfWorkRequestKey] = UnitOfWork; UnitOfWork.Begin(); } 

then for transaction I returned it from temporary data like this.

 public override void OnActionExecuted(ActionExecutedContext filterContext) { var unitOfWork = (IUnitOfWork)filterContext.Controller.TempData[UnitOfWorkRequestKey]; try { if (filterContext.Exception == null) { unitOfWork.Complete(); } } finally { unitOfWork.Dispose(); filterContext.Controller.TempData[UnitOfWorkRequestKey] = null; } } 

So my question is:
In System.Web.Http Web Api Action Filter (using HttpActionContext ) - is there an equivalent location to store my service instance, so I can get the same instance when the action is completed?

+4
source share
1 answer

In System.Web.Http Web Api Action Filter (using HttpActionContext) - is there an equivalent location to store my service instance, so I can get the same instance when the action was performed?

No no. The whole point of the API is that it must be stateless. This is rule number 1. If you need to use Session or TempData in the API, you are probably doing something very wrong in terms of design.

Also, you should not use TempData in your MVC application for this task. TempData is used when you need to save information between multiple requests. In your case, this is the same request. Therefore, you should have used the HttpContext to store this information:

 public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Items[UnitOfWorkRequestKey] = UnitOfWork; } 

and then:

 public override void OnActionExecuted(ActionExecutedContext filterContext) { var unitOfWork = (IUnitOfWork) filterContext.HttpContext.Items[UnitOfWorkRequestKey]; try { if (filterContext.Exception == null) { unitOfWork.Complete(); } } finally { unitOfWork.Dispose(); filterContext.Controller.TempData[UnitOfWorkRequestKey] = null; } } 

Ok, now that we have installed your MVC application here, how to achieve the same thing in the web API using the Request.Properties collection:

 public override void OnActionExecuting(HttpActionContext actionContext) { actionContext.Request.Properties[UnitOfWorkRequestKey] = UnitOfWork; } 

and then:

 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var unitOfWork = (IUnitOfWork) actionExecutedContext.Request.Properties[UnitOfWorkRequestKey]; try { if (actionExecutedContext.Exception == null) { unitOfWork.Complete(); } } finally { unitOfWork.Dispose(); } } 
+17
source

All Articles