【问题标题】:405 Method Not Allowed - when sending object from jQuery to rest WCF405 Method Not Allowed - 当从 jQuery 发送对象到 rest WCF
【发布时间】:2019-08-10 19:26:13
【问题描述】:

这个问题被问了很多,但即使我尝试了他们提供的解决方案,我仍然得到一个错误。

我正在发送一个带有 Person 对象作为参数的发布请求,但我得到:

405 - 方法不允许错误"

代码:

合同:

 [ServiceContract]
 public interface IPayMentService
 {
      [OperationContract]
      [WebInvoke(Method = "POST",
          UriTemplate = "/AddPerson",
          BodyStyle = WebMessageBodyStyle.Wrapped,
          RequestFormat = WebMessageFormat.Json,
          ResponseFormat = WebMessageFormat.Json)]
      void AddPerson(Person person); 
 }

 [DataContract]
 public class Person
 {
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public int Age { get; set; }
    [DataMember]
    public String Name { get; set; }
 }

服务:

public class PayMentService : IPayMentService
{
    public void AddPerson(Person person) 
    {
        //..logic
    }
}

客户:

 $(document).ready(function() {
 var person = {Id: 1, Age : 13, Name: "zag"};

  $.ajax({
        url: 'http://localhost:64858/PayMentService.svc/AddPerson',
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify(person),
        dataType: 'json'
    })
});

谢谢,

【问题讨论】:

标签: c# jquery rest wcf


【解决方案1】:

尝试在 global.asax 文件中使用此代码:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
        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();
        }
    }

【讨论】:

    【解决方案2】:

    如果您的 Option 请求没有返回合适的状态,该请求也会失败。 为确保选项请求返回 200 状态,您最好更改状态码。 您也可以在 web.config 中添加这些标头。

     <system.webServer>
    
      <httpProtocol>  
      <customHeaders>  
        <add name="Access-Control-Allow-Origin" value="*" />  
      <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="*"/>
            </customHeaders>  
    </httpProtocol>
      </system.webServer>
    
      protected void Application_EndRequest(object sender, EventArgs e)
        {
                     if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.StatusCode = 200;
            }
    
        }
    

    如果你对跨域请求不熟悉,可以参考mdn

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    【讨论】:

      猜你喜欢
      • 2016-04-12
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 2021-06-20
      • 2018-06-28
      • 2016-06-15
      • 1970-01-01
      相关资源
      最近更新 更多