我在MVC 5中创建了一个项目。我想从jquery中调用一个动作方法。此操作将返回json对象。在jQuery ajax id
中parse4cn1
但在浏览器中抛出错误。如果我设置
dataType: 'jsonp',
投掷
阻止跨源请求:同源策略禁止在http:.....
读取远程资源
我在web配置和应用程序开始请求中设置属性,如
dataType: 'json'
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>
我的jQuery请求
public class ProductApiController : Controller
{
[HttpGet]
public JsonResult GetProductJson(int Productid, string Key)
{
return this.Json(new { Errorcode = "1", data = "data json success" }, JsonRequestBehavior.AllowGet);
}
谢谢
答案 0 :(得分:2)
在过滤器中添加
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
{