I have a rather strange scenario. I use autofac in a project that has both MVC4 pages and a Web API endpoint. Autofac manages the scope of my model object (which, in turn, controls the scope of the database context), and I configured it for InstancePerHttpRequestand InstancePerApiRequestso that only one database context is created for each query. This means that all the database objects that I use are bound to the same query (context is an EF6 context).
Here is my strange scenario: the application supports the "proxy" function, when one user can become different during the duration of the page request. To make sure that you even AuthorizeAttributepay attention to this, I catch the request in the event PostAuthenticateRequestand execute a switch IPrincipal, as well as configure the user who uses my database context. The problem is with checking permissions: I need to ask my database if the user is allowed a proxy server as the user whom they would like the proxy server. The code more or less looks like this:
protected void Application_PostAuthenticateRequest()
{
if (!User.Identity.IsAuthenticated)
return;
var cookie = Request.Cookies.Get(Controllers.ProxyController.ProxyCookie);
var model = DependencyResolver.Current.GetService<Model.MyModel>();
var user = model.Users.Where(u => u.username == User.Identity.Name).FirstOrDefault();
model.User.Current = model.User.Actual = user;
if (cookie != null)
{
var proxyAs = model.Users.Where(u => u.username == cookie.Value).FirstOrDefault();
if (user != null && proxyAs != null)
{
if (user.CanProxyAs(proxyAs))
{
string[] roles;
if (proxyAs != null)
{
roles = proxyAs.groups.SelectMany(g => g.roles).Select(r => r.name).ToArray();
}
else
{
roles = new string[0];
}
model.User.Actual = user;
model.User.Current = proxyAs;
HttpContext.Current.Items[Controllers.ProxyController.ProxyUser] = User;
Thread.CurrentPrincipal = HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(cookie.Value), roles);
}
}
}
}
The problem is in the part where I use DependencyResolverto resolve the model object.
MVC... DependencyResolver . AutofacDependencyResolver - AutofacDependencyResolver, MVC.
-API, . AutofacDependencyResolver , InstancePerHttpRequest. , WebAPI GlobalConfiguration.Configuration.DependencyResolver, AutofacWebApiDependencyResolver API AutoFac Web API. , , , WebAPI, model.User, MVC DependencyResolver .
, . , . MVC DependencyResolver API -?
, web-api HttpRequestMessage (.. Action). PostAuthenticateRequest.
- autofac, InstancePerApiRequest, InstancePerHttpRequest?
, :
- , API MVC
HttpRequestMessage PostAuthenticateRequest, API, ?
, , .
EDIT: , System.Net.Http.DelegatingHandler WebAPI, HttpRequestMessage PostAuthenticateRequest. , , - api .