Examine Request Headers with ServiceStack

2019-03-27 20:42发布

问题:

What is the best way to inspect the Request Headers for a service endpoint?

ContactService : Service

Having read this https://github.com/ServiceStack/ServiceStack/wiki/Access-HTTP-specific-features-in-services I'm curious as to the preferred way to get to the Interface.

Thank you, Stephen

回答1:

Inside a ServiceStack Service you can access the IHttpRequest and IHttpResponse objects with:

public class ContactService : Service 
{
    public object Get(Contact request)
    {
        var headerValue = base.Request.Headers[headerKey];

        //or the same thing via a more abstract (and easier to Mock):
        var headerValue = base.RequestContext.GetHeader(headerKey);
    }
}

The IHttpRequest is a wrapper over the underlying ASP.NET HttpRequest or HttpListenerRequest (depending if you're hosting on ASP.NET or self-hosted HttpListener). So if you're running in ASP.NET you can get the underlying ASP.NET HttpRequest with:

var aspnetRequest = (HttpRequest)base.Request.OriginalRequest;
var headerValue = aspnetRequest.Headers[headerKey];