Jquery web api中阻止跨源请求
我有一个Web Api项目(名称TestApi) 当我调试这个项目时,当我输入这个URL时,就会得到JSON数据 现在我想使用Jquery从另一个MVC项目(名称为:callTestApi)调用这个api方法,我已经编写了这行代码Jquery web api中阻止跨源请求,jquery,ajax,asp.net-mvc,asp.net-web-api,Jquery,Ajax,Asp.net Mvc,Asp.net Web Api,我有一个Web Api项目(名称TestApi) 当我调试这个项目时,当我输入这个URL时,就会得到JSON数据 现在我想使用Jquery从另一个MVC项目(名称为:callTestApi)调用这个api方法,我已经编写了这行代码 $.ajax({ type: 'GET', contentType: 'application/json; charset=utf-8', url: 'http://localho
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: 'http://localhost:31310/api/Authors/',
success: function (data) {
var getAll = data;
alert(data[0].Name)
},
error: function (data) {
alert('Error in getting result');
}
});
我已经在TestApi项目中启用了CORS。
看这里
[EnableCors(origins: "http://localhost", headers: "*", methods: "*")]
public class AuthorsController : ApiController
{
private TestWebApiContext db = new TestWebApiContext();
// GET: api/Authors
public IQueryable<Author> GetAuthors()
{
return db.Authors;
}
}
我已经启用了Webapiconfig文件
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableCors();
}
尝试在API的web.config中的
标记之后添加此项
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
可能config.EnableCors()代码>不够。尝试:
[启用CORS(来源:“*”,标题:“*”,方法:“*”)
我认为不允许使用localhost。尝试列出标题,而不是使用通配符。您能告诉我们您得到的错误是什么吗?无论如何,这会使您暴露于XSS攻击,如前所述。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>