C# 将逻辑调用上下文从OWIN管道传递到WebApi控制器

C# 将逻辑调用上下文从OWIN管道传递到WebApi控制器,c#,asp.net,asynchronous,asp.net-web-api,owin,C#,Asp.net,Asynchronous,Asp.net Web Api,Owin,我正试图按照Stephen Cleary的帖子传递逻辑调用上下文的上下文信息(使用CallContext.LogicalSetData(CallContextKey,value));并受到中代码的启发 该值将通过OWIN管道可用,但在调用进入WebApi控制器时不可用,该值未设置 我还注意到,在控制器中设置断点时,在调用堆栈中看不到OWIN管道。显然,ASP.NET正在单独的调用上下文上进行控制器调用 所以 ASP.NET为什么(以及如何)将调用上下文从OWIN管道隔离到WebApi控制器 如

我正试图按照Stephen Cleary的帖子传递逻辑调用上下文的上下文信息(使用
CallContext.LogicalSetData(CallContextKey,value)
);并受到中代码的启发

该值将通过OWIN管道可用,但在调用进入WebApi控制器时不可用,该值未设置

我还注意到,在控制器中设置断点时,在调用堆栈中看不到OWIN管道。显然,ASP.NET正在单独的调用上下文上进行控制器调用

所以

  • ASP.NET为什么(以及如何)将调用上下文从OWIN管道隔离到WebApi控制器

  • 如何将上下文数据从管道传递到控制器


我不太清楚将上下文数据从管道传递到控制器是什么意思,但如果您已经使用了Microsoft.AspNet.Identity,您可以利用IAppBuilder.createPerowContext将对象注册到管道

当我想通过Owin管道将上下文对象传递给WebApi控制器时,我通常会这样做:

startup.cs

//Registration of a delegate factory
 app.CreatePerOwinContext<Foo>(Factory.CreateFoo);
//Contextual Object
public static Foo CreateFoo(IdentityFactoryOptions<Foo> options, IOwinContext context)
    {
      //Owin Context is available here
    }
 public FooController()
    {
        var fooObj= HttpContext.Current.GetOwinContext().Get<Foo>();
    }
//代理工厂的注册
app.CreatePerOwinContext(Factory.CreateFoo);
factory.cs

//Registration of a delegate factory
 app.CreatePerOwinContext<Foo>(Factory.CreateFoo);
//Contextual Object
public static Foo CreateFoo(IdentityFactoryOptions<Foo> options, IOwinContext context)
    {
      //Owin Context is available here
    }
 public FooController()
    {
        var fooObj= HttpContext.Current.GetOwinContext().Get<Foo>();
    }
//上下文对象
公共静态Foo CreateFoo(IdentityFactoryOptions选项,IOwinContext上下文)
{
//这里提供了Owin上下文
}
控制器.cs

//Registration of a delegate factory
 app.CreatePerOwinContext<Foo>(Factory.CreateFoo);
//Contextual Object
public static Foo CreateFoo(IdentityFactoryOptions<Foo> options, IOwinContext context)
    {
      //Owin Context is available here
    }
 public FooController()
    {
        var fooObj= HttpContext.Current.GetOwinContext().Get<Foo>();
    }
publicfoocontroller()
{
var fooObj=HttpContext.Current.GetOwinContext().Get();
}

希望有帮助

我花了几天时间才弄明白为什么API控制器中的CallContext是清晰的,直到我读了这篇文章:


如果两个中间件在不同的IIS阶段运行,它们将具有不同的CallContext。


如果您在IIS上托管OWIN,并且希望在所有中间件中使用相同的请求上下文,那么请使用旧的
HttpContext.Current

“如果两个中间件在不同的IIS阶段运行,它们将具有不同的CallContext。”这似乎是真的,但您能告诉我文档(或代码)中的位置吗这将证明这一点。只是为了加深理解。无论如何,非常感谢您的输入,您为我节省了大量时间。我没有找到任何文档。我只是做了一些实验,得出了这个结论。