我在MVC 5中创建了一个项目。我想从jquery调用一个操作方法。此操作将返回json对象。在jQuery中ajax id
dataType: 'jsonp',
但在浏览器中抛出错误。如果我设置
dataType: 'json'
投掷
阻止跨来源请求:同源策略不允许读取http:…..上的远程资源。。。。。
我在web配置和应用程序开始请求中设置属性,如
void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
}
在web.config
:中
<system.webServer>
<modules>
<remove name="FormsAuthentication"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
我的控制器动作
public class ProductApiController : Controller
{
[HttpGet]
public JsonResult GetProductJson(int Productid, string Key)
{
return this.Json(new { Errorcode = "1", data = "data json success" }, JsonRequestBehavior.AllowGet);
}
我的jQuery请求
$.ajax({
type: 'GET',
url: 'http://--------------',
cache: false,
data: "id:2",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.data);
},
error: function (response) {
alert("Error");
}
});
感谢
将其添加到过滤器中
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, origin, authorization, accept, client-security-token");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Max-Age", "1000");
base.OnActionExecuting(filterContext);
}
控制器应为
[AllowCrossSiteJson]
public JsonResult Getvalue(string Key, int id)
{
Result objresult = new Result();
try
{