javascript - 使用 jQuery.getJson 获取 Web API

标签 javascript jquery asp.net api

我是 ASP.NET Web API 的初学者。
无法使用jQuery.getJson()获取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)
    {
    }
}

} }

最佳答案

您需要在 WebAPI 中启用 CORS。首先,安装这个Nuget - https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors然后将此行添加到 WebApiConfig:

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

WebApi配置:

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 }
        );
    }

关于javascript - 使用 jQuery.getJson 获取 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33143365/

相关文章:

mysql - MySQL 的 ASP.Net 提供程序

javascript - 如何在express.js中打开多个url?

javascript - 使用 jQuery/JavaScript 替换字符串的一部分

javascript - .替换问题

c# - 使用带有 $ 符号的变量反序列化 JSON

c# - 重定向到 ASP.NET 中的其他页面时确认框不起作用

javascript - 如何从 HTML 中的内部选项获取隐藏输入

javascript - JQuery - 查找具有给定数量兄弟元素的元素

javascript - 使用用户定义函数时 map 消失

jQuery 左右滑动 - 编写代码的更简单方法?