4

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..!!

  • 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 – dotnetom Sep 27 '15 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, – mayur manudhanya Sep 27 '15 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..? – mayur manudhanya Sep 27 '15 at 15:35
  • Have you seen this post: http://stackoverflow.com/questions/11242797/calling-mvc4-web-api-from-a-normal-html-file-outside-the-project ? – David Tansey Sep 27 '15 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.! – mayur manudhanya Sep 28 '15 at 06:03
  • hi can you please copy/paste error message rather then error occured? – Suresh Sep 28 '15 at 07:14

1 Answers1

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..!');
            }
          });
});
  • 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. – Peter Sep 28 '15 at 19:25
  • 1
    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 – mayur manudhanya Sep 29 '15 at 09:47