Harun
Harun

Reputation: 5179

POST methods from web api not getting called.

I'm trying to call a POST method from a web api (created inside a MVC4 project) and not able to access it.

My web api config is as follows,

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

I'm trying to call the following method,

    [HttpPost]
    public bool Delete(Int64 Id)
    {           
        return true;
    }

All the GET methods are getting called.

When i'm trying to access it the browser is showing,

"http 405 Method not allowed"

When seeing the Response it shows like,

{"Message":"The requested resource does not support http method 'GET'."}

Please help me out.

Upvotes: 0

Views: 4456

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

When i'm trying to access it the browser is showing

Well, that's normal. The browser sends GET request. Your method can only be invoked with a POST request.

Here's how a sample HTTP request might look like:

POST /someresource/delete/123 HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 0
Connection: close

You can try the request in Fiddler or write a sample HTTP client that will send a POST request.

Ah, and by the way, why not sticking to standard RESTful conventions:

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

and your action:

public bool Delete(Int64 Id)
{           
    return true;
}

and to invoke it:

DELETE /someresource/123 HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 0
Connection: close

Notice that the standard RESTful convention dictates that the action name should not be used in your routes. It is the HTTP verb that decides which action to be invoked. So your actions should be named accordingly to the HTTP verb. In your example you want to delete some resource with a specified id, so your controller action should be named Delete (as it is currently) and it should be accessible through the DELETE HTTP verb.

Upvotes: 4

Related Questions