【问题标题】:Cross Site ajax request not working跨站点ajax请求不起作用
【发布时间】:2013-06-03 20:29:41
【问题描述】:

您好,我需要有两个独立的项目,一个是 MVC 项目,另一个是 WEB API 项目。两者都将放在单独的解决方案中。

当我尝试从 mvc 项目向 web api 项目进行 ajax 调用时出现了我的问题,并且出现此错误:

OPTIONS http://localhost:54599/api/Account/IsCurrentUserAuthenticated 405

(不允许的方法)jquery-1.9.1.min.js:5 选项 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-Origin 不允许http://localhost:61620

经过一番研究,我想出了这个过滤器,它被添加到控制器中,以便我需要拨打电话:

 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);
}

我该如何解决我的问题?

【问题讨论】:

标签: javascript jquery asp.net-mvc asp.net-web-api


【解决方案1】:
var options = {
        url: url,
        type: 'GET',
        contentType: "application/json; charset=utf-16",
        dataType: 'jsonp',
        xhrFields: xhrFields
    };

使用跨域时需要使用jsonp 数据类型。

【讨论】:

  • JSONP 与他正在使用的 CORS 无关。他应该设置crossDomain: true 标志。
【解决方案2】:

跨域请求需要使用dataType: 'jsonp'

【讨论】:

  • 如果使用 CORS 正确设置且浏览器支持,则跨域不需要 JSONP。
  • @epascarello 确实如此。但是,由于问题的标题是“跨站点 ajax 请求不起作用”,所以我的回答符合这个标题。
猜你喜欢
  • 2014-04-18
  • 2010-09-24
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多