简体   繁体   中英

How to get request headers using Owin Self Host Web API

I have ported an existing web api project - which has been run using IIS - to OWIN (selfhosted). I´m using dependency injection (unity) and have implemented a service which needs some information from the current request´s header (ie var x = HttpContext.Current.Request.Headers["xxx"] ).

Since HttpContext is not available in OWIN (which makes sense) - how can I get the current request? Please keep in mind that I do need this information inside an injected service (not inside a controller and an OWIN middleware module - owincontext).

Your controller should inherit from ApiController , which has a Request property that will be populated for each request. So from within your controller action just use Request.Headers[...] .

Create a sample class like below

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

In the controller something like below should work

var owincontext = request.GetOwinContext().Environment;

var headerParser= new HeaderParser(owincontext); headerParser.GetEmployeeNoFromHeader()

What we have done is we have implemented interface IHttpControllerActivator.Create like below, so it runs for all controller class, The controller is generated by dependency injection 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;
    }

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