HTTP CODE 405 (Method Not Allowed), When I sent PO

2019-05-24 08:24发布

问题:

Web.config

 <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
  </customHeaders>
</httpProtocol>
<handlers>
  <remove name="WebDAV"/>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

Controller

  [EnableCors(origins: "http://domain/api/Clients", headers: "*", methods: "*")]
public class ClientsController : ApiController
{
    private ParaNewnergyEntities db = new ParaNewnergyEntities();

    // GET: api/Clients
    public IEnumerable<Client> GetClient()
    {
        return db.Client.ToList();
    }
    [HttpPost]
    public IHttpActionResult PostClient(String Username, String Password)
    {
        Client c = new Client
        {
            Username = Username,
            Password = Password
        };

        db.Client.Add(c);
        db.SaveChanges();
        return Ok(c);
    }

WebApiConfig.cs

     public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.EnableCors();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }

Ajax

   var sendData={
            Username:"gx",
            Password:"gx"
        };
        $.ajax({
            url: "http://domain/api/Clients",
            type: "POST",
            data: sendData,
            success: function (d) {
                $("#msg").html(d);
                console.log(d);
            }
        });

Browser Error:

  POST http://domain/api/Clients 405 (Method Not Allowed)

I can get API by GET method. It is very weirdo that I can get response from API by POST method without Any Parameter. Otherwise, I just got http error 405.

In addition, I get http error 405 from DELETE and PUT method, too. Only GET and Option return httpcode 200.

回答1:

Check this : Troubleshooting HTTP 405 Errors after Publishing Web API 2 Applications

MVC-Web API: 405 method not allowed


There is problem with the way you are passing data to your method, as you are trying to pass multiple parameter you should try as below

you ajax call need to be like

var client = {
    Username:"gx",
    Password:"gx"
}
$.ajax(
{
    url: "http://domain/api/Clients",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(client),
    success: function (result) {
        alert(result);
    }
});

and you web api method will be like this

[HttpPost]
    public IHttpActionResult PostClient(Client client)
    {
        db.Client.Add(c);
        db.SaveChanges();
        return Ok(c);
    }

Also check post here : http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods