Ivan-Mark Debono Ivan-Mark Debono - 3 months ago 11
ASP.NET (C#) Question

Attribute routing doesn't work on Put request

In my simple WebApi project I'm only using attribute routing by doing this:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
}
}


I have this controller:

[RoutePrefix("myprefix")]
public class SomeController : ApiController
{
[HttpGet]
[Route("v2/test/dosomething")]
public IHttpActionResult TestIt()
{
return Ok("Test ok");
}

[HttpPut]
[Route("v2/myaction/somethingelse")]
public async Task<IHttpActionResult> MyAction(string message)
{
return Ok("Put ok");
}
}


I'm accessing the above as follows:

GET http://localhost/myapp/myprefix/v2/test/dosomething
PUT http://localhost/myapp/myprefix/v2/myaction/somethingelse


The
GET
works fine. However, the
PUT
returns:

{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost/myapp/myprefix/v2/myaction/somethingelse'.",
"MessageDetail": "No action was found on the controller 'Some' that matches the request."
}


What am I missing?

Answer

The default way of sending data with PUT requests are through the body. So first step is to add a [FromBody] infront of the parameter. If you sending data with content type of json then I would create a object as parameter instead which contains a message parameter.

public class jsonMessage
{
    public string message {get; set; }
}

Use the jsonMessage class as the parameter with the [FromBody] in the controller method as this

[HttpPut]
[Route("v2/myaction/somethingelse")]
public async Task<IHttpActionResult> MyAction([FromBody]jsonMessage message)
{
    return Ok("Put ok");
}

Then when making request to the endpoint add a request body as this {"message":"waaaasssaaa"} and send it with Content-Type: 'application/json'