【问题标题】:405 Method not allowed -while calling wcf service using jquery ajax method405 方法不允许 - 使用 jquery ajax 方法调用 wcf 服务时
【发布时间】:2014-03-30 16:44:52
【问题描述】:

当我尝试从 $.ajax 方法调用 wcf 服务时,我得到以下异常。

1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed) 

2. Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource.

AJAX 编码

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(request),
        async: false,
        url: "http://localhost:65201/Empservice.svc/getEmployee",
        crossdomain: true,
        success: function (data) {
            try {
                response = data;
            }
            catch (e) {
                alert(e);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Excpetion " + errorThrown + XMLHttpRequest);
        }
    });

【问题讨论】:

  • url 你指定的不正确使用 url:"your url"
  • 您提出跨域请求,但您将数据类型定义为 JSON。更改为 JSONP,如果您尝试访问 localhost 文件,请在 url ex:url"yourIpAddress/Empservice.svc/getEmployee" 中提及您的 IP 地址
  • 当在 ajax 调用中使用 url 作为字符串模式之后,我们也面临相同的响应
  • 我们使用 jsonp 而不是 json 然后下面的方法不会触发它。成功:函数(数据){尝试{响应=数据; } 捕捉 (e) { 警报(e); } },

标签: jquery ajax json wcf jsonp


【解决方案1】:

为了避免 405 Method not allowed 错误,请尝试在 wcf 服务 Global.asax 文件中添加以下编码。它对我有用

 protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                           "Accept, Content-Type,customHeader");

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                          "POST,GET,OPTIONS");

            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
                          "172800");

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials",
                          "true");

            HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers",
                          "customHeader");

            HttpContext.Current.Response.AddHeader("Content-type",
                         "application/json");

            HttpContext.Current.Response.End();
        }
        else
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                           "Accept, Content-Type,customHeader");


            HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers",
                          "customHeader");

            HttpContext.Current.Response.AddHeader("Content-type",
                         "application/json");

        }


    } 

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 2014-07-17
    • 2019-10-27
    • 2012-04-21
    • 2016-06-13
    • 2011-01-13
    • 2012-04-30
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多