我已将现有的web api项目(已使用IIS运行)移植到OWIN(自动托管)。我使用依赖注入(unity)并实现了一项服务,该服务需要当前请求标头中的一些信息(即var x = HttpContext.Current.Request.Headers["xxx"]
)。
由于HttpContext
在OWIN中不可用(这是有道理的) - 我如何获得当前请求?请记住,我确实需要在注入的服务中使用此信息(不在控制器和OWIN中间件模块内 - owincontext)。
答案 0 :(得分:2)
您的控制器应继承自ApiController
,其Request
属性将为每个请求填充。因此,在您的控制器操作中,只需使用Request.Headers[...]
。
答案 1 :(得分:0)
创建一个如下所示的示例类
public class HeaderParser
{
IDictionary<string, object> _requestContext;
IDictionary<string, string[]> _headers;
public HeaderParser(IDictionary<string, object> requestContext)
{
_requestContext = requestContext;
_headers = requestContext["owin.RequestHeaders"] as IDictionary<string, string[]>;
}
public string GetEmployeeNoFromHeader()
{
if (_headers != null && _headers.ContainsKey("X-EmployeeNo") && _headers["X-EmployeeNo"] != null && _headers["X-EmployeeNo"].Length > 0)
{
return _headers["X-EmployeeNo"][0];
}
else
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
response.Content = new StringContent("EMPLOYEE NO NOT AVAILABLE IN REQUEST");
throw new HttpResponseException(response);
}
}
}
在控制器中,下面的内容应该可以正常工作
var owincontext = request.GetOwinContext().Environment;
var headerParser = new HeaderParser(owincontext); headerParser.GetEmployeeNoFromHeader()
我们所做的是我们已经实现了接口IHttpControllerActivator.Create,如下所示,所以它运行所有控制器类,控制器是由依赖注入windsor castle生成的
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
var owincontext = request.GetOwinContext().Environment;
var headerParser= new HeaderParser(owincontext);
var logger = _dpendencyManager.Resolve(typeof(IPOSLogger)) as IPOSLogger;
var executionContext = new ExecutionContext(logger, owincontext,headerParser.GetEmployeeNoFromHeader());
var controller =
(IHttpController)_dpendencyManager.Resolve(controllerType, new { context = executionContext });
//var controller =
// (IHttpController)_dpendencyManager.Resolve(controllerType);
request.RegisterForDispose(
new Release(
() => _dpendencyManager.Release(controller)));
return controller;
}