Add a custom response header in ApiController

后端 未结 6 1701
难免孤独
难免孤独 2021-02-05 02:41

Until now, I had a GET method that looked like the following:

protected override async Task GetAll(QueryData query)
{
              


        
相关标签:
6条回答
  • 2021-02-05 02:48

    You can use a custom ActionFilter that will allow you to send custom headers and access the HttpContext:

    public class AddCustomHeaderFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
           actionExecutedContext.Response.Content.Headers.Add("name", "value");
        }
    }
    
    0 讨论(0)
  • 2021-02-05 02:50

    You can explicitly add custom headers in a method like so:

    [HttpGet]
    [Route("home/students")]
    public HttpResponseMessage GetStudents()
    {
           // Get students from Database
    
           // Create the response
            var response = Request.CreateResponse(HttpStatusCode.OK, studends);
    
            // Set headers for paging
            response.Headers.Add("X-Students-Total-Count", studends.Count());
    
           return response;
    }
    

    For more information read this article: http://www.jerriepelser.com/blog/paging-in-aspnet-webapi-http-headers/

    0 讨论(0)
  • 2021-02-05 02:59

    Simple solution is to write just this:

    HttpContext.Current.Response.Headers.Add("MaxRecords", "1000");
    
    0 讨论(0)
  • 2021-02-05 02:59

    What you need is:

    public async Task<IHttpActionResult> Get() 
    { 
        var response = Request.CreateResponse();
        response.Headers.Add("Lorem", "ipsum");
    
        return base.ResponseMessage(response); 
    }
    

    I hope this answers your question.

    0 讨论(0)
  • 2021-02-05 03:03

    Alternatively, it’s better to leverage DelegatingHandler if it is something you need to perform on every response. Because it will work on the request/response pipeline and not on the controller/action level. In my case I must add some headers with every response, so I did what I described. See code snippet below

    public class Interceptor : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
            response.Headers.Add("Access-Control-Allow-Origin", "*");
            response.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,PUT,OPTIONS");
            response.Headers.Add("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token, content-type");
            return response;
        }
    
    }
    

    And you would be requiring to add this handler in WebApiConfig

        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.MessageHandlers.Add(new Interceptor());
            }
        } 
    
    0 讨论(0)
  • 2021-02-05 03:12

    I have entered comments, here is my complete answer.

    You will need to create a custom filter and apply that to your controller .

    public class CustomHeaderFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
           var count = actionExecutedContext.Request.Properties["Count"];
           actionExecutedContext.Response.Content.Headers.Add("totalHeader", count);
        }
    }
    

    In your Controller

      public class AddressController : ApiController
            {
                public async Task<Address> Get()
                {
                   Request.Properties["Count"] = "123";
                }
        }
    
    0 讨论(0)
提交回复
热议问题