简体   繁体   中英

ASP.NET WebApi: How to check and create per-request context?

In a self hosted ASP.NET Web Api , how can I:

  1. Detect from a class if there's an "ambient" web api context. This is needed to avoid passing in metadata information on every service call. I'm looking for the equivalent of

    System.Web.HttpRequest.Current != null

  2. How can I attach metadata information associated with the current request. Again some of this metadata is just so prevalent that including them on every method and calls is way too painful. Think transaction, multi-tenant architecture and credentialings. I need a way to make this sort of information flow through between requests without cluttering the code.

    In another word I also need the equivalent of this as explained here :

    HttpContext.Current.Items["user" + X.ToString()]

I think I can still access them, as long as the WebApi is hosted on IIS, but I have got these self hosted and I need a way to keep track of the ambient UoW information - how can I do so?

A few notes:

  1. I have also contemplated using per request DI and injecting a request context into the managers, there are however a ton of legacy code that wasn't set up for that (some of which are static) and I don't have the guts to blow up production by doing such a major refactor.
  2. I have also used a thread static, static variable - the problem with such is that the thread gets recycled, and the process hosts multiple services, some of which aren't even WebApi... so sometimes my managers thought it's handling a WebApi request when in fact it's serving a WCF one.

HttpRequestMessage实例具有“属性”字典,该字典用于保存任意的每个请求上下文。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM