shamnad
shamnad

Reputation: 338

Cross-Origin Requests in ASP.NET Web API

I have a api controller in my mvc application and I tried to post data to the api, but I am getting the problem of Cross-Origin Requests in ASP.NET Web API . Here is my error

XMLHttpRequest cannot load http://192.168.0.44:100/api/name. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53114' is therefore not allowed access. The response had HTTP status code 405.

I have installed Cross-Origin Requests in ASP.NET Web API 2

my api code

namespace Restaurant.Controllers{
[EnableCors(origins: "http://192.168.0.44:100", headers: "*", methods: "get,post")]

    public class OrderController : ApiController  
    {
        public Test Post( string name,int age)  
        {
            Test test = new Test()
            {
               Name=name,
               Age=age
            };
            db.test.Add(test);
            db.SaveChanges();
            return test;
        }}

WebApiConfig

public static void Register(HttpConfiguration config)
{
    config.EnableCors();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });         
    config.Formatters.Add(new BrowserJsonFormatter());                       
}

View

 <script type ="text/javascript">
 function add() {      
        var DatatTest = {
        name: $("#txtname").val(),
        age: $("#txtage").val()
    };
    $.ajax({            
        url: 'http://192.168.0.44:100/api/name',
        type: 'Post',
        data: JSON.stringify(DatatTest),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert("ok");},
        error: function (x, y, z) {
            alert("error");}
    });
}
</script>

web.config

httpProtocol>
  <customHeaders>               
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

Now I am getting this error

XMLHttpRequest cannot load http://192.168.0.44:100/api/Order. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53114' is therefore not allowed access. The response had HTTP status code 500.

Where's my mistake?

Upvotes: 1

Views: 2072

Answers (2)

Kesavarapu Venkatesh
Kesavarapu Venkatesh

Reputation: 242

It is the Error that shows while calling web API. there are two reasons behind it.

  1. CORS
  2. Headers

we can enable the CORS in webapiconfig.cs file

CONFIG.EnableCors(cors);

to resolve headers we should allow WEBAPI to allow all the Headers as below

 EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");

Reference Article

Upvotes: 3

Libin Joseph
Libin Joseph

Reputation: 7392

Try the following steps.

In web.config

config.EnableCors();

In your controller add this

 [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]

Note: origins should be the client address, and not the sever address ,and make sure you do not add a black slash at the end of origins URL.

Upvotes: 2

Related Questions