3

I'm a beginner of ASP.NET Web API.
Fail to use jQuery.getJson() to get ASP.NET Web API

this failed:

var url = "http://localhost:56110/api/Values"; $.getJSON(url, function (data) { $("#locMsg").text("success"+data); });` 

I though it is because of cross-domain request, but this succeeded:

var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=dog&tagmode=any&format=json&jsoncallback=?"; $.getJSON(url, function (data) { $("#locMsg").text("success"); }); 

then I tried to add "jsoncallback=?" but also failed:

var url = "http://localhost:56110/api/Values?jsoncallback=?"; $.getJSON(url, function (data) { $("#locMsg").text("success"+data); }); 

ValuesController:

namespace WebApplication1.Controllers{ public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }` `// GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } } 

} }

1
  • Changing your client side code to use JSONP only works if the server supports JSONP. Commented Oct 15, 2015 at 9:16

1 Answer 1

1

You need enable CORS in you WebAPI. Firstly, install this Nuget - https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors and then add this line to WebApiConfig:

config.EnableCors(new EnableCorsAttribute("*","*","*")); 

WebApiConfig:

public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.EnableCors(new EnableCorsAttribute("*","*","*")); // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.