asp.net – 使用HttpRequestMessage.Properties传递每个请求的上下文

前端之家收集整理的这篇文章主要介绍了asp.net – 使用HttpRequestMessage.Properties传递每个请求的上下文前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Web API应用程序中,我使用Castle Windsor提供使用PerWebRequest生命周期配置的服务,并且一切正常在IIS上运行.

但是,当我使用ASP.NET Web API Self Host(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
    }
}
原文链接:https://www.f2er.com/aspnet/251235.html

猜你在找的asp.Net相关文章