Pipeline
Pipeline

Reputation: 1059

Get a custom header in angular $http from web api controller

I am trying to pass a piece of information along with my content in my HttpResponseMessage like:

        string jsonFiles = JsonConvert.SerializeObject(listFiles);
        HttpResponseMessage response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StringContent(jsonFiles)
        };
        response.Headers.Add("Key", "Value");

        return response;

However in my angular call and response I cannot see the "Key" header in response.config.headers or response.headers. Any idea why?

  $http.get("/api/Locker").then(function (response) {
        console.log(response);
        console.log(response.headers);
        console.log(response.config.headers);
  });

In my Startup.cs I do have:

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config); 

Upvotes: 0

Views: 1743

Answers (3)

yilik01
yilik01

Reputation: 138

I am using WebApi version 5.2.3. To export a response header, you can try creating a custom attribute, for example

public class CustomHeadersAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        actionExecutedContext.Response.Headers.Add("Access-Control-Expose-Headers", "<Your Custom Key>");
        base.OnActionExecuted(actionExecutedContext);
    }
}

Then on your controller or wherever you need it, just add

[CustomHeaders]
public HttpResponseMessage GetMethod() { ... }

Upvotes: 0

Parthasarathy
Parthasarathy

Reputation: 2818

As per the documentation response.config returns the config used while sending the request. response.headers is a function. Try using response.headers("Key") and see if it helps.

Upvotes: 1

Federico Dipuma
Federico Dipuma

Reputation: 18265

You have to explicitly add the custom header to your CORS policy, or AngularJS will be unable to read it. Change this:

app.UseCors(CorsOptions.AllowAll);

To this:

var policy = new CorsPolicy
{
    AllowAnyHeader = true,
    AllowAnyMethod = true,
    AllowAnyOrigin = true,
    SupportsCredentials = true
};

policy.ExposedHeaders.Add("MyHeader");

app.UseCors(new CorsOptions
{
    PolicyProvider= new CorsPolicyProvider
    {
        PolicyResolver = c => Task.FromResult(policy)
    }
});

Upvotes: 0

Related Questions