嗨,我需要有两个独立的项目,一个是 MVC 项目,另一个是 WEB API 项目。两者都将放在单独的解决方案中。
当我尝试从 mvc 项目向 web api 项目进行 ajax 调用时出现我的问题,并且出现此错误:
OPTIONS http://localhost:54599/api/Account/IsCurrentUserAuthenticated 405
(不允许的方法)jquery-1.9.1.min.js:5 OPTIONS 访问控制允许
http://localhost:54599/api/Account/IsCurrentUserAuthenticated
来源http://localhost:61620
不允许来源。jquery-1.9.1.min.js:5 XMLHttpRequest 无法加载http://localhost:54599/api/Account/IsCurrentUserAuthenticated
。Access-Control-Allow- Originhttp://localhost:61620
不允许 Origin。
经过一番研究,我想出了这个过滤器,它被添加到控制器中,以便我需要拨打电话:
public class AllowCrossSiteJsonWebApiAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext filterContext)
{
filterContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
string rqstMethod = filterContext.ActionContext.ControllerContext.Request.Method.Method.ToUpperInvariant();
if (rqstMethod == "OPTIONS" || rqstMethod == "POST")
{
filterContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST, OPTIONS");
filterContext.Response.Headers.Add("Access-Control-Allow-Headers", "X-Requested-With, Accept, Access-Control-Allow-Origin, Content-Type");
}
if (rqstMethod == "OPTIONS")
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.OK);
return;
}
base.OnActionExecuted(filterContext);
}
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
这是我从客户那里打来的电话:
function fetch(url) {
xhrFields = {
withCredentials: true // pass auth cookies to server over ajax req
};
var options = {
url: url,
type: 'GET',
contentType: "application/json; charset=utf-16",
dataType: 'json',
xhrFields: xhrFields
};
return $.ajax(options);
}
我该如何解决我的问题?