Thiago Thiago - 1 year ago 80
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:

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) {

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.

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 Source

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(); \\<==============

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download