Ajax Post: 405 Method Not Allowed

2019-03-18 07:20发布

Within my API Controller called Payment, I have the following method:

[HttpPost]
public HttpResponseMessage Charge(Payment payment)
{
    var processedPayment = _paymentProcessor.Charge(payment);
    var response = Request.CreateResponse(processedPayment.Status != "PAID" ? HttpStatusCode.ExpectationFailed : HttpStatusCode.OK, processedPayment);
    return response;
}

In my HTML page I have:

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost:65396/api/payment/charge",
        data: $('#addPayment').serialize(),
        dataType: "json",
        success: function (data) {
            alert(data);
        }
    });

Whenever I fire the POST, I get

"NetworkError: 405 Method Not Allowed - http://localhost:65396/api/payment/charge"

What am I missing?

Thank you.

UPDATE

Here's the routing information (default)

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

3条回答
戒情不戒烟
3楼-- · 2019-03-18 08:00

I had the same problem with my controller. The only thing which is different is the ending of the URL. Add "/" to "http://localhost:65396/api/payment/charge" at the end, that helped me

查看更多
\"骚年 ilove
4楼-- · 2019-03-18 08:08

Most likely your routing is not configured for the action to be invoked. Hence the request ends up in nowhere and ASP.NET Web API sends a blank-out message "method not allowed".

Can you please update the question with your routing?


UPDATE

As I thought! You are sending to http://localhost:65396/api/payment/charge while you need to send to http://localhost:65396/api/payment - assuming your controller is called PaymentController.

Note that route does not have action.

查看更多
登录 后发表回答