标签:
MVC实现方式:
[ActionAllowOrigin]
[HttpPost]
public JsonResult Cooperation()
{
return json();
}
在方法前面加上[ActionAllowOrigin] 这个方法是自定义的继承自AuthorizeAttribute
public class ActionAllowOriginAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
var origin = filterContext.HttpContext.Request.Headers["Origin"];
filterContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin",origin);
}
}
这样就支持跨域了;调用方法如下:
function test()
{
$.ajax({
url: "http://www.baidu.com/KnotHireManger/Cooperation",//这里是提交url
type: "post",//jsonp必须是get方式,post不支持,注意
// dataType: "json",
data: {name:$("#Name").val(),Phone:$("#Phone").val()},
success: function (msg) {
console.log(msg)
}
}
//问题:
如果遇到浏览器不支持的话就把origin换成*号 如下:
filterContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin","*");
标签:
原文地址:http://www.cnblogs.com/sunqiang/p/5413516.html