Error - Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

I was working on a project where I wrote a web method and called this web method from JQuery.
But I found this error -

"Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response."

In debugging, I couldn't find any issue with the code neither in C# nor in JQuery.
Then I got below solution.

This error is due Cross-Origin Resource Sharing (CORS). To know more about Cross-Origin Resource Sharing (CORS) click here.

In web.config file search for  <system.webServer> and add below section if you want to allow for all domain

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>

If you wish to allow a particular domain then use below lines.

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="www.domain-name.com" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>

After applying this solution my code works.



Comments

Popular

C# 6.0 New Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners