Qingwei
Qingwei

Reputation: 510

Only Get request is allowed, others returning 404 not found

I have a scenario like this

ASP.net Web API project using C# VS 2013 IIS Express 8.0 hosted on localhost

I am having 3 Controllers

Controller A serves HttpGet , controllerA(string id) Controller B serves HttpPost, controllerB(string id) Controller C serves HttpPost, controllerC(string id, double x)

only the 1st is working, while Post request always return 404, anyone know whats wrong? is it due to security setting on IIS ?

the code is as follow

Controllers code

[HttpPost]
[ActionName("UpdatePosition")]
public string UpdateBus(string id)
{
    return " request is received - post";
}

Client function call

<script>
    function sendPutRequest() {
        $.ajax({
            url: 'http://localhost:54284/api/bus/updatePosition/',
            type: 'POST',
            data: { id: 'test123' },
            success: function (result) {
                $('#output').append(result);
            }
        });
    }
</script>

Upvotes: 0

Views: 650

Answers (1)

Raja Nadar
Raja Nadar

Reputation: 9499

By default, Web API reads a primitive parameter value (int, bool, string etc.) for a POST action from the URL.

In your case, it probably doesn't find one. So it defaults to a parameterless action method, and it doesn't find it. You're passing the parameter in the request body. to solve for this:

Use the [FromBody] attribute for your parameter.

public string UpdateBus([FromBody]string id)

If you don't want to use this attribute, the other option is to send the parameter in the query string in your AJAX request.

url: 'http://localhost:54284/api/bus/updatePosition?id=' + 'test123'

please note that only one [FromBody] attribute can be used for the parameters. if you have multiple primitive parameters, try to create a class for all of them and have the class as the parameter.

Upvotes: 2

Related Questions