2018年4月25日 星期三

[Web API] Custom http header in request or response


 ASP.NET    Web API  


Introduction


How to receive custom http header from http request or append a new one on http response in ASP.NET Web API 2.



Environment


Visual Studio 2017 community 15.3.3
ASP.NET Web API2



Implement


In Action

Get custom http header’s value from http request

var headers = Request.Headers;
IEnumerable<string> values = null;
if (headers.TryGetValues("my-token", out values))
{
    var token = values.FirstOrDefault();
}


However, you can use this extension: Raz.HeaderAttribute, to get the custom header like this,

public async Task<Something> Get([FromHeader("my-token")] string token)
{

}

PS. This feature is available on ASP.NET Core now.

Append custom http header’s value to http response

// Create response
var response = Request.CreateResponse(HttpStatusCode.OK, myContent);
response.Headers.Add("my-token", "xxxxxxxxxxxx");



ActionFilter Attribute

Also we can implement an ActionFilterAttribute to apply the custom http header handling to actions.

public class MyFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
        {
            // Current request headers
            var headers = actionContext.Request.Headers;
            IEnumerable<string> values = null;
            if (headers.TryGetValues("my-token", out values))
            {
                var token = values.FirstOrDefault();

                
//Optional: Set the custom value to BaseController's public property
var baseController = actionContext.ControllerContext.Controller as BaseController;
if (baseController != null)
{
baseController.MyToken = token;
}
            }
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionContext)
        {
            actionContext.Response.Headers.Add("my-token", "xxxxxxxxx");
        }
}




Reference




沒有留言:

張貼留言