使用 jQuery.getJson 获取 Web API [英] Use jQuery.getJson to get Web API

查看:28
本文介绍了使用 jQuery.getJson 获取 Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 ASP.NET Web API 的初学者.
使用jQuery.getJson()获取ASP.NET Web API

失败<块引用>

失败:

//在file:///C:/Users/lil/Desktop/index.html"var url = "http://localhost:56110/api/Values";$.getJSON(url, function (data) {$("#locMsg").text("成功"+数据);});`

<块引用>

这成功了:

//在http://localhost:56110/index.html"var url = "http://localhost:56110/api/Values";$.getJSON(url, function (data) {$("#locMsg").text("成功"+数据);});

<块引用>

虽然是跨域请求,但是成功了:

//在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("成功");});

<块引用>

然后我尝试添加jsoncallback=?"但也失败了:

//在file:///C:/Users/lil/Desktop/index.html"var url = "http://localhost:56110/api/Values?jsoncallback=?";$.getJSON(url, function (data) {$("#locMsg").text("成功"+数据);});

<块引用>

值控制器:

命名空间 WebApplication1.Controllers{公共类 ValuesController : ApiController{//获取 api/值公共 IEnumerable得到(){返回新字符串[] { "value1", "value2" };}``//获取 api/values/5公共字符串 Get(int id){返回值";}//POST api/值public void Post([FromBody]string value){}//放置 api/values/5public void Put(int id, [FromBody]string value){}//删除 api/values/5公共无效删除(int id){}}

}}

解决方案

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

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

WebApiConfig:

公共静态类WebApiConfig{公共静态无效注册(HttpConfiguration 配置){config.EnableCors(new EnableCorsAttribute("*","*","*"));//Web API 配置和服务//将 Web API 配置为仅使用不记名令牌身份验证.config.SuppressDefaultHostAuthentication();config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));//Web API 路由config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{id}",默认值:新 { id = RouteParameter.Optional });}

I'm a beginner of ASP.NET Web API.
Fail to use jQuery.getJson() to get 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 it is because of cross-domain request, but this 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 I tried to add "jsoncallback=?" but also 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
{
    // 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)
    {
    }
}

} }

解决方案

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

这篇关于使用 jQuery.getJson 获取 Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆