asp.net - 使用HttpRequestMessage.Properties承载每个请求的上下文

标签 asp.net dependency-injection castle-windsor asp.net-mvc-4 asp.net-web-api

在Web API应用程序中,我使用CaSTLe Windsor提供配置了PerWebRequest生存期的服务,并且在IIS上一切正常。

但是,当我使用ASP.NET Web API自助主机(Beta)package时,我需要创建一个自定义生存期,以便为每个HTTP请求确定这些服务的范围。

如何使用HttpRequestMessage.Properties承载每个请求的上下文?

最佳答案

我建议您使用消息处理程序将一些对象设置为HttpRequestMessage.Property:

public class MyApplication : HttpApplication
{
    protected void Application_Start()
    {
        RegisterHttpMessageHandlers(GlobalConfiguration.Configuration);
    }
    public void RegisterHttpMessageHandlers(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new MyMessageHandler());
    }
}

public static class MyHttpMessageHandlerExtensions
{
    public static class HttpPropertyKey
    {
        public static readonly string MyProperty = "MyCompany_MyProperty";
    }

    public static MyContext GetContext(this HttpRequestMessage request)
    {
        return (MyContext)request.Properties[HttpPropertyKey.MyProperty ];
    }

    public static void SetContext(this HttpRequestMessage request, MyContext ctx)
    {
        request.Properties[HttpPropertyKey.MyProperty] = ctx;
    }
}
public class MyMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.SetContext(new MyContext(){/*some your data*/});
        return base.SendAsync(request, cancellationToken);
    }
}

public class MyController: ApiController
{
    public object GetData()
    {
        MyContext ctx = this.Request.GetContext(); // the extenstion method is used
    }
}

关于asp.net - 使用HttpRequestMessage.Properties承载每个请求的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10563188/

相关文章:

asp.net - "405 Method not allowed"- 使用 ASP.NET jQuery ajax POST 时

asp.net - 地理定位网络服务建议

asp.net-mvc - Aspnet 样板/Aspnet 零慢 (IoC)

asp.net-mvc - 带参数的 MvcContrib Windsor 设置组件

caSTLe-windsor - CaSTLe温莎流利注册: AllTypes and type forwarding

asp.net - 我为什么要使用 RIA 服务共享代码?

asp.net - 禁用 TLS 1.0 会破坏 ASP.NET 应用程序

c# - 尝试使用 MEF 将依赖项注入(inject) IIS 托管的 WCF 服务

spring - MapStruct 映射器未在 Spring 单元测试中注入(inject)

asp.net-mvc-3 - 是否可以将太多存储库注入(inject) Controller ?