4

I'm new to ASP.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..!!

6
  • 1
    Can you change failure: to error: (failure is incorrect parameter name) and add alert(data) as method body? If you have an error it should tell you what that is Commented Sep 27, 2015 at 14:18
  • @dotnetom i have replaced the failure: with error but and it kinda works but it returning a function code form jquery lib, Commented Sep 27, 2015 at 15:33
  • @dotnetom I've used the same jquery code in the same projects index view file and it works properly but my Html file is out of the solution and it throws error why..? Commented Sep 27, 2015 at 15:35
  • Have you seen this post: stackoverflow.com/questions/11242797/… ? Commented Sep 27, 2015 at 17:01
  • hey @DavidTansey i've seen the post and have modified my jquery code but it still goes in the error block and i dont know why.! Commented Sep 28, 2015 at 6:03

1 Answer 1

2

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..!');
            }
          });
});
Sign up to request clarification or add additional context in comments.

2 Comments

If you are using this in a live public website, you should consider changing the origins part of your CORS declaration to only list the domains that you all access from, otherwise anyone will be able to access your API on their website.
yes @PeterBailey i know but i want to create this api to provide data to mobile devices that is why i am allowing it to all websites but i will be providing authentication

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.