Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asp.net - 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.

How can I carry per-request context using the HttpRequestMessage.Properties?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...