如何在 Web api MVC 6 中启用跨源请求
How to enable cross-origin requests in web api MVC 6
我想使用 jsonp 从外部访问我的网站 api 以绕过跨站点脚本。
[HttpGet("{email}")]
public User Get(string email)
{
var user = (from usr in db.User
join co in db.UserDetails on usr.id equals co.userId
where co.email.Equals(email) || usr.email.Equals(email)
select usr).FirstOrDefault();
return user;
}
这是我的 javascript 代码
jQuery.ajax({
type: "GET",
url: "http://localhost:54381/api/userapi/test1@test.com",
dataType: "jsonp",
success: function (response) {
var t = JSON.parse(response);
alert(t.name);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error" + textStatus + " " + errorThrown);
}
});
因为我低于错误
"parsererror" errorThrown Error:
jQuery110206458149312522913_1441780598078 was not called
这里有什么问题?
如何设置为webapireturnjsonp格式的结果?或者必须启用代码的跨域来处理它?有什么我需要做的设置吗?
做 google 我发现 JsonpMediaTypeFormatter 可以用来获取数据。我如何在 MVC 6 web api.
中进行设置
mvc 6 web 似乎还有一些问题 api,我正在弄清楚之后我会在这里添加。
您是否尝试过 Produces
属性?
似乎 Produces
属性允许您 return 特定格式,而不管当前配置的格式化程序如何。
Produces 适用于 Method level
(我还没有测试它们是否适用于 Controller level
)。
[HttpGet("{email}")]
[Produces("application/jsonp")]
public Customer Get(string email)
{
...
}
我想使用 jsonp 从外部访问我的网站 api 以绕过跨站点脚本。
[HttpGet("{email}")]
public User Get(string email)
{
var user = (from usr in db.User
join co in db.UserDetails on usr.id equals co.userId
where co.email.Equals(email) || usr.email.Equals(email)
select usr).FirstOrDefault();
return user;
}
这是我的 javascript 代码
jQuery.ajax({
type: "GET",
url: "http://localhost:54381/api/userapi/test1@test.com",
dataType: "jsonp",
success: function (response) {
var t = JSON.parse(response);
alert(t.name);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error" + textStatus + " " + errorThrown);
}
});
因为我低于错误
"parsererror" errorThrown Error: jQuery110206458149312522913_1441780598078 was not called
这里有什么问题? 如何设置为webapireturnjsonp格式的结果?或者必须启用代码的跨域来处理它?有什么我需要做的设置吗? 做 google 我发现 JsonpMediaTypeFormatter 可以用来获取数据。我如何在 MVC 6 web api.
中进行设置mvc 6 web 似乎还有一些问题 api,我正在弄清楚之后我会在这里添加。
您是否尝试过 Produces
属性?
似乎 Produces
属性允许您 return 特定格式,而不管当前配置的格式化程序如何。
Produces 适用于 Method level
(我还没有测试它们是否适用于 Controller level
)。
[HttpGet("{email}")]
[Produces("application/jsonp")]
public Customer Get(string email)
{
...
}