2015-10-15 77 views
0

我是ASP.NET Web API的初學者。
未能使用jQuery.getJson()獲得ASP.NET Web API使用jQuery.getJson獲取Web API

這種失敗:

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

這個成功:

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

我雖是因爲跨域請求,但這種成功:「jsoncallback =」

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

然後我試圖添加但也失敗了:

//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) 
    { 
    } 
} 

}}

+0

更改您的客戶端代碼使用JSONP只能如果服務器支持JSONP。 – Quentin

回答

1

您需要啓用CORS在你的WebAPI。首先,安裝此的NuGet - 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 } 
     ); 
    }