Thiago Thiago - 3 months ago 16
C# Question

Why can't I get the headers in Web Api?

I've searched a lot and can't figure it out what I am missing.

I'm trying to send headers in an ajax call:

$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
headers: { "Authorization": "98765", "X-My-Secret-Token": "WhyCantIGetThis", "JustAnotherTest": "314987" },
//beforeSend: function (request) {
// request.setRequestHeader("Authorization", "98765"); -> I tried this way too
//},
success: function (data) {
$('#value1').html(data);
}
})


And get that in:

public override void OnActionExecuting(HttpActionContext actionContext)
{
var header_X_My_Secret_Token = actionContext.Request.Headers.SingleOrDefault(x => x.Key == "X-My-Secret-Token");
var header_Authorization = actionContext.Request.Headers.SingleOrDefault(x => x.Key == "Authorization");
var header_JustAnotherTest = actionContext.Request.Headers.SingleOrDefault(x => x.Key == "JustAnotherTest");

var heeder_Authorization2 = actionContext.Request.Headers.Authorization;
}


But it's all null. Does anyone can tell me why? Thanks.
[Edit]

I can get the header in same domain ajax call. But I need to get it in cross domain too. How do that? Thanks

Answer

For anyone who's still searching an answer...

I just had to enable CORS:

Install-Package Microsoft.AspNet.WebApi.Cors

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            EnableCors(); \\<==============

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api