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(); } }
source share