zoukankan      html  css  js  c++  java
  • Carrying per-request context using the HttpRequestMessage.Properties

    In a Web API application, I use Castle Windsor to supply services configured with PerWebRequest lifetime and everything works fine on IIS.

    However, when I use the ASP.NET Web API Self Host (Beta) package I need to create a custom lifetime in order to scope those services per HTTP request.

    I'd suggest you using a message handler to set some your object into 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
        }
    }
  • 相关阅读:
    COJ 1002 WZJ的数据结构(二)(splay模板)
    生成网络流图
    最小费用最大流MCMF zkw费用流
    COJ 2003 选根 (树的重心)
    最小费用最大流MCMF 最小增广
    PDO 基础知识
    使 用 Jquery 全选+下拉+单选+事件+挂事件
    搜 房 网 站 设 计 练 习
    百分比进度条
    在PHP系统里连接MySQL 数据访问,+ + + + + 数据删除
  • 原文地址:https://www.cnblogs.com/lenmom/p/8797653.html
Copyright © 2011-2022 走看看