0

I'm trying to create a basic REST POST using asp.net Web API, but it is returning error status: 0. Also it looks like fails the AJAX request

My controller:

[HttpPost]
    public myData Post( myData m)
    {
        return m;
    }

My class:

public class CLData
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

My HTML request:

    <html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
    <script>
        //form encoded data
         var dataType = 'application/x-www-form-urlencoded; charset=utf-8';
         var data = $('form').serialize();

         //JSON data
         var dataType = 'application/json; charset=utf-8';
         var data = {
            FirstName: 'Andrew',
            LastName: 'Lock',
            Age: 31
         }

         console.log('Submitting form...');
         $.ajax({
            type: 'POST',
            url: 'http://localhost:52884/api/contact',
            dataType: 'json',
            contentType: dataType,
            data: data,
            success: function(result) {
                console.log('Data received: ');
                console.log(result);
            },
            error: function(error){
                console.log('Error: ');
                console.log(error);
            }
        });
    </script>
</body>

</html>

I don't know why my console log is:

Submitting form..
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:52884/api/contact. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Error: 
Object with status: 0

Does anyone know what I am doing wrong? I'm just trying to learn Web API, that's why this example is so simple.

user6824563
  • 735
  • 6
  • 25
  • 47
  • Just as an experiment, try replacing 'url: 'http://localhost:52884/api/contact' with 'url: '/api/contact'. Assuming that your application is actually hosting both the API endpoint and serving the page. If it is not serving the page, you need to enable cross-origin requests in your application. – JD Davis Oct 13 '17 at 00:42
  • Still the same problem. – user6824563 Oct 13 '17 at 01:12

1 Answers1

1

If your application is not serving up both the web view and the API endpoint, you'll need to enable Cross-Origin-Requests. To do so, you need to configure Cors in your WebAPI project. You can find a detailed breakdown of how to do so on the Microsoft Reference Page.

However, the gist is to install the nuget pacakge Microsoft.AspNet.WebApi.Cors. You can do so by executing Install-Package Microsoft.AspNet.WebApi.Cors. From there, you will update your WebApiConfig Register method to include config.EnableCors(); at the top.

Next, you'll decorate your controller class with the [EnableCors] attribute. From there, you should be able to make cross-origin requests.

JD Davis
  • 3,517
  • 4
  • 28
  • 61