Click here to Skip to main content
14,739,403 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have a web api which has a Post method in it.
So from another webpage i'm posting json data to this API using jquery ajax as below -
$.ajax({  
    type: "POST",  
    url: "http://localhost:4046/Values/Mymethods",  
    data: jsondata,  
    dataType: 'json'  
}).complete(function (msg) {  
});

This is working fine and getting the result from API.

The issue happens when I add an custom header in to this as below -
$.ajax({  
             type: "POST",  
             url: "http://localhost:4046/Values/Mymethods",  
             data: jsondata,  
             dataType: 'json',  
             header: { 'Token': 'asasaad' }  
         }).complete(function (msg) {  
         });

Now this is throwing cross domain error like below -

XMLHttpRequest cannot load http://localhost:4046/Values/My methods. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2769' is therefore not allowed access. The response had HTTP status code 405.

I have provided <add name="Access-Control-Allow-Origin" value="*" /> header in web.config

I have created Web API in MVC 4.

Hope someone has got an solution for this.

Thanks in advance.

What I have tried:

Tried providing
<add name="Access-Control-Allow-Origin" value="*" /> header in web.config
Posted
Updated 25-Aug-20 22:34pm
Comments
F-ES Sitecore 9-Mar-17 8:24am
   
In which config? You have a client project and an API project. It needs to go in the API project and there are additional access settings that allow the use of custom headers so you probably need to add that too.
Midhun T P 9-Mar-17 23:59pm
   
As i'm not using web API 2, i'm not able to use CORS. Everything is working fine, if custom header is not passed.Issue is happening when I pass this header.
makoychan 25-Aug-20 15:44pm
   
im experiencing the same situation, were you able to resolve midhun?

1 solution

We can send cross domain AJAX requests using JSONP. Below is the simple JSONP Request:


$.ajax({  
             type: "POST",  
             url: "http://localhost:4046/Values/Mymethods",  
             data: jsondata,  
             dataType: 'jsonp',  
             header: { 'Token': 'asasaad' }  
         }).complete(function (msg) {  
         });
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900