mayur manudhanya
mayur manudhanya

Reputation: 120

Jquery Ajax is unable to get data from ASP.NET WEB API

I'm new to APS.NET MVC WEB API programming.

So here is my problem, I have Created an ASP.NET WEB API project with the following Code

 public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<Employee> Get()
    {
        return new List<Employee>()
        {
            new Employee(){ EmpId=1,EmpName="xyz" },
            new Employee(){EmpId=2,EmpName="abc"}
        };
    }

    // GET api/values/5
    public Employee Get(int id)
    {
        return new Employee() { EmpId = id, EmpName = "xyz" };
    }

}

simple right..!!

the next thing i did is created an html file and write an ajax method to get data from web api

 $(function () {
            var obj = {};
            $.ajax({

                type: "GET",
                url: "http://localhost:2797/api/values/1",
                data: JSON.stringify(obj),
                dataType: "JSON",
                contentType: "application/json; charset=UTF-8",
                success: function (data) {
                    alert(data.EmpName);
                },
                failure: function (data) {
                    alert("Error Occured");
                }

            });

        });

now here is the problem my jquery script is able to contact to webapi because the breakpoints breaks when ever the html page get Refreshed and it also returns the value but for some unknown reason the alert message in Success function wont hit. and i don't know why

Please Help

Thanks in Advance..!!

Upvotes: 4

Views: 1142

Answers (1)

mayur manudhanya
mayur manudhanya

Reputation: 120

i have finally found the solution

first goto tools->Nuget Package Manager -> Package Manager Console

type in this Command Install-Package Microsoft.AspNet.WebApi.Cors -IncludePrerelease

then in WebApiConfig.cs add this Line config.EnableCors();

now decorate you apicontroller with this attribute [EnableCors(origins:"*",headers:"*",methods:"*")]

But then while consuming api with post method we may have some issues with the cors Attribute

so to avoid it. we can Declare the cors Attribute globally

like in WebApiConfig.cs write this piece of code

var cors= new EnableCorsAttribute(origins:"*",headers:"*",methods:"*");
config.EnableCors(cors);

now the jquery code

$(document).read(function(){
    jquery.support.cors=true;
    $.ajax({
           type:"GET",
           url:"http://localhost:63300/api/values/1",
           crossDomain:true,
           contentType:"application/json; charset=utf-8",
           dataType:"json",
           success:function(data){
                alert(data);
           },
            error:function(data){
                alert('Error Occured..!');
            }
          });
});

Upvotes: 2

Related Questions