Skip to content Skip to sidebar Skip to footer

How To Set The Origin Request Header

I want to send an AJAX request to a remote API. function Gettest(CourseID) { var param = { 'CourseID': CourseID}; param = JSON.stringify(param); $.ajax({ type:

Solution 1:

In short: you cannot.

As described on MDN; Origin is a 'forbidden' header, meaning that you cannot change it programatically.

You would need to configure the web server to allow CORS requests.

To enable CORS, add this to your Web.config

<system.webServer><!-- Other stuff is usually located here as well... --><httpProtocol><customHeaders><addname="Access-Control-Allow-Origin"value="*" /></customHeaders></httpProtocol><system.webServer>

Alternatively, in Global.asax.cs

publicclassWebApiApplication : System.Web.HttpApplication
{
    protectedvoidApplication_Start()
    {
        /* Some register config stuff is already located here */
    }

    // Add this method:protectedvoidApplication_BeginRequest()
    {
        HttpContext.Current.Response.AddHeader
            (name: "Access-Control-Allow-Origin", value: "*");            
    }
}

Solution 2:

Just as Baksteen stated, you cannot change this header value in JavaScript. You would have to edit your server configuration to allow cross origin requests.

But: After reading your comments, I think you need a solution for debugging and testing only.

In that case, you can use Chrome and start it with special unsafe parameters. If you provide this parameters to Chrome, it will allow you cross domain requests.

Do not use this chrome instance for other things than testing your page!

chrome --disable-web-security--user-data-dir

I tried several Add-ons for Firefox and Chrome, but they did not work with recent versions of the browsers. So I recommend to switch to chrome and use the parameters above to test your API calls.


If you are interested in a more powerful solution, you may want to use a Debugging Proxy, like Fiddler from Telerik. You may write a custom rule, so Fiddler changes your headers before the request leaves your PC. But you have to dig into the tool, before you can use all its powers. This may be interesting, because it may help you out on more than just this debugging issue.

Post a Comment for "How To Set The Origin Request Header"