问题
I'm trying to pass contextual information on the logical call context (using CallContext.LogicalSetData(CallContextKey, value)) as per Stephen Cleary's post http://blog.stephencleary.com/2013/04/implicit-async-context-asynclocal.html; and inspired by the code in https://github.com/neuecc/OwinRequestScopeContext.
The value will be available through out the OWIN pipeline, but it is not available when the call enters the WebApi controller, the value is not set.
I also noticed that when setting a breakpoint in the controller, I can't see the OWIN pipeline in the call stack. Apparently, ASP.NET is making controller calls on a separate call context.
So,
Why (and how) does ASP.NET isolate the call context from OWIN pipeline to the WebApi controller?
How can I pass contextual data from Pipeline to the controller?
回答1:
It took me several days to find out why the CallContext is clear in the API controller, until I read this article: http://www.asp.net/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline
If two middleware runs in different IIS stage, they will have different CallContext.
If you are hosting OWIN on IIS and want the same request context in all middlewares, well, use the old HttpContext.Current instead.
回答2:
I'm not really sure what you mean by passing contextual data from Pipeline to the controller but maybe if you already use Microsoft.AspNet.Identity, you could leverage the use of IAppBuilder.CreatePerOwinContext in order to register your object to the pipeline.
I use to do something like that when I want to pass my contextual object through Owin Pipeline to WebApi Controllers:
startup.cs
//Registration of a delegate factory
app.CreatePerOwinContext<Foo>(Factory.CreateFoo);
factory.cs
//Contextual Object
public static Foo CreateFoo(IdentityFactoryOptions<Foo> options, IOwinContext context)
{
//Owin Context is available here
}
controller.cs
public FooController()
{
var fooObj= HttpContext.Current.GetOwinContext().Get<Foo>();
}
Hope it helps !
来源:https://stackoverflow.com/questions/29194836/passing-logical-call-context-from-owin-pipeline-to-webapi-controller