Reputation: 1059
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
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
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
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