1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

I hope i have done that .can i use IP for origins ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.