-1

This question is asked a lot, but even though I tried the solutions they offered, I still get an error.

I am sending a post request with a Person object as a parameter, but i get:

405 - Method Not Allowed error"

code:

contract:

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

service:

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

client:

 $(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'
    })
});

Thanks,

4

2 Answers 2

0

try with this code in the global.asax file:

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

If your Option request doesn't return suitable status, the request will also fail. To ensure option request returns 200 status, you had better change the status code. You could also add these headers in 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;
        }

    }

If you are not familiar with cross region request, you could refer to mdn

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.