javascript - Use jQuery.getJson to get Web API -


this question has answer here:

i'm beginner of asp.net web api.
fail use jquery.getjson() asp.net web api

this failed:

//in "file:///c:/users/lil/desktop/index.html" var url = "http://localhost:56110/api/values"; $.getjson(url, function (data) {     $("#locmsg").text("success"+data); });` 

this succeeded:

//in "http://localhost:56110/index.html" var url = "http://localhost:56110/api/values"; $.getjson(url, function (data) {     $("#locmsg").text("success"+data); }); 

i though because of cross-domain request, succeeded:

//in "file:///c:/users/lil/desktop/index.html" 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 tried add "jsoncallback=?" failed:

//in "file:///c:/users/lil/desktop/index.html" var url = "http://localhost:56110/api/values?jsoncallback=?"; $.getjson(url, function (data) {     $("#locmsg").text("success"+data); }); 

valuescontroller:

namespace webapplication1.controllers{ public class valuescontroller : apicontroller {     // api/values     public ienumerable<string> get()     {         return new string[] { "value1", "value2" };     }`      `// 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)     {     } } 

} }

you need enable cors in webapi. firstly, install nuget - https://www.nuget.org/packages/microsoft.aspnet.webapi.cors , add line webapiconfig:

config.enablecors(new enablecorsattribute("*","*","*")); 

webapiconfig:

public static class webapiconfig {     public static void register(httpconfiguration config)     {          config.enablecors(new enablecorsattribute("*","*","*"));          // web api configuration , services         // configure web api use 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 }         );     } 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -