【问题标题】:Method not allowed (http error 405) , wcf , rest service , post method方法不允许(http 错误 405)、wcf、rest 服务、post 方法
【发布时间】:2017-01-29 14:54:31
【问题描述】:

我正在尝试从 html 和 ajax 脚本调用在 wcf 中实现的 post 方法。 我可以从 postman 调用。我尝试了 google , stackoverflow previous questions ,但没有一个对我有帮助。

我来自 wcf 的 web.config :

  <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
      </webScriptEndpoint>
    </standardEndpoints>

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,HEAD,PUT,OPTIONS" />
  </customHeaders>
</httpProtocol>

以下是我在html中的ajax调用

  $.ajax({
      type: "POST",
      url: "http://localhost:8078/SportsClubDefault.svc/Validate",
      data: st,
       contentType: "application/json; charset=utf-8",
       processData:true,
      dataType: "json",
      success: function (data) {
          // Play with response returned in JSON format
            alert('Login success');
      },
       error: function (xhr) {
             alert('Login failed');
         }
     });

以下图片来自邮递员

以下是html控制台的图片

【问题讨论】:

    标签: c# ajax rest wcf post


    【解决方案1】:

    这是一个 CORS 问题,您可以通过在 wcf 服务上创建 global.asax 文件来启用 cors,

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
    
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2017-10-16
    • 2017-11-18
    • 2018-12-20
    • 2012-10-25
    • 2020-07-26
    • 2016-06-13
    • 2011-01-13
    • 2019-07-05
    • 2013-12-05
    相关资源
    最近更新 更多