How to add custom header to ASP.NET Core Web API response

丶灬走出姿态 提交于 2019-12-29 03:32:28

问题


I am porting my API from Web API 2 to ASP.NET Core Web API. I used to be able to add a custom header in the following manner:

  HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
  response.Headers.Add("X-Total-Count", count.ToString());
  return ResponseMessage(response);

How does one add a custom header in ASP.NET Core Web API?


回答1:


You can just hi-jack the HttpContext from the incoming Http Request and add your own custom headers to the Response object before calling return.

If you want your custom header to persist and be added in all API requests across multiple controllers, you should then consider making a Middleware component that does this for you and then add it in the Http Request Pipeline in Startup.cs

public IActionResult SendResponse()
{
    Response.Headers.Add("X-Total-Count", "20");

    return Ok();
}    



回答2:


There is an example for simple GET action which returns top X records from some list as well as the count in the response header X-Total-Count:

using System;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication.Controllers
{
    [Route("api")]
    public class ValuesController : Controller
    {
        [HttpGet]
        [Route("values/{top}")]
        public IActionResult Get(int top)
        {
            // Generate dummy values
            var list = Enumerable.Range(0, DateTime.Now.Second)
                                 .Select(i => $"Value {i}")
                                 .ToList();
            list.Reverse();

            var result = new ObjectResult(list.Take(top))
            {
                StatusCode = (int)HttpStatusCode.OK
            };

            Response.Headers.Add("X-Total-Count", list.Count.ToString());

            return result;
        }
    }
}

URL looks like http://localhost:3377/api/values/5 and results (for 19 dummy records generated, so X-Total-Count value will be 19) are like:

["Value 18","Value 17","Value 16","Value 15","Value 14"]



回答3:


A custom attribute can be a good way.

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.2

public class AddHeaderAttribute : ResultFilterAttribute
{
    private readonly string _name;
    private readonly string _value;

    public AddHeaderAttribute(string name, string value)
    {
        _name = name;
        _value = value;
    }

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        context.HttpContext.Response.Headers.Add(_name, new string[] { _value });
        base.OnResultExecuting(context);
    }
}

Then use it like this on your API method

[AddHeader("X-MyHeader", "123"]

If you have a common header you can just extend this class :

public class MySpecialHeaderAttribute : AddHeaderAttribute
{
    public MySpecialHeaderAttribute() : base("X-MyHeader", "true")
    {
    }
}



回答4:


FWIW, if you have an ApiController, instead of a Controller, here is how you can do it:

public class InfoController : ApiController
{
    // Without custom header
    public IHttpActionResult MyMethod(..)
    {
        var myObject= GetMyResult();
        return Ok(myObject);
    }

    // With custom header
    public IHttpActionResult MyMethod(..)
    {
        var myObject = GetMyResult();

        // inspired from https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/content-negotiation#how-content-negotiation-works
        var negotiator = Configuration.Services.GetContentNegotiator();
        var result = negotiator.Negotiate(typeof(TypeOfMyObject), Request, Configuration.Formatters);
        var msg = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ObjectContent<TypeOfMyObject>(myObject, result.Formatter,result.MediaType.MediaType)
        };

        msg.Headers.Add("MyCustomHeader", "MyCustomHeaderValue");
        return ResponseMessage(msg);
    }
}


来源:https://stackoverflow.com/questions/46183171/how-to-add-custom-header-to-asp-net-core-web-api-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!