JQuery Ajax cannot get data from ASP.NET API

I am new to APS.NET MVC WEB API programming.

So here is my problem, I 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 was create 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 that my jquery script can contact webapi because breakpoints break when the html page ever gets Refreshhed and it also returns a value, but for some unknown reason the warning message in the Success function will not be deleted . and I do not know why

Please, help

Thanks at Advance .. !!

+4
1

,

goto → Nuget →

Install-Package Microsoft.AspNet.WebApi.Cors -IncludePrerelease

WebApiConfig.cs config.EnableCors();

apicontroller [EnableCors(origins:"*",headers:"*",methods:"*")]

, api post, cors

. cors

WebApiConfig.cs,

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

jquery

$(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..!');
            }
          });
});
+2

Source: https://habr.com/ru/post/1609188/


All Articles