使用jQuery.getJson来获取Web API
使用jQuery.getJson来获取Web API
我是ASP.NET Web API的初学者。
\n无法使用jQuery.getJson()
来获取ASP.NET Web API
。\n
\n这个失败了:\n
\n
var url = "http://localhost:56110/api/Values"; $.getJSON(url, function (data) { $("#locMsg").text("成功"+data); });`
\n
\n我认为这是因为跨域请求,但这个成功了:\n
\n
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=dog&tagmode=any&format=json&jsoncallback=?"; $.getJSON(url, function (data) { $("#locMsg").text("成功"); });
\n
\n然后我尝试添加\"jsoncallback=?\",但仍然失败了:\n
\n
var url = "http://localhost:56110/api/Values?jsoncallback=?"; $.getJSON(url, function (data) { $("#locMsg").text("成功"+data); });
\n
\nValuesController:\n
\n
namespace WebApplication1.Controllers{ public class ValuesController : ApiController { // GET api/values public IEnumerableGet() { 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) { } }
\n}\n}
从上述内容中可以看出,问题的原因是需要在WebAPI中启用CORS(跨域资源共享)。解决方法是通过安装NuGet包"Microsoft.AspNet.WebApi.Cors"并添加一行代码到WebApiConfig文件中。具体的解决方法如下所示:
首先,安装NuGet包"Microsoft.AspNet.WebApi.Cors"。可以通过以下链接进行安装:https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors
然后,在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 } ); } }
通过以上的方法,可以在WebAPI中启用CORS,并解决相关的问题。