6

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

但是,当我使用 ASP.NET Web API Self Host (Beta)时,我需要创建一个自定义生命周期,以便根据 HTTP 请求确定这些服务的范围。

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

4

1 回答 1

11

我建议您使用消息处理程序将一些对象设置为 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
    }
}
于 2012-05-12T14:37:50.810 回答