I have WebAPI 2 application. How can I specify 2 or more POST methods?
I have the following WebApiConfig:
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
and API Controller:
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
[Route("Post1")]
[HttpPost]
public IQueryable<string> Post1(string str)
{
return null;
}
[Route("Post2")]
[HttpPost]
public IQueryable<string> Post2(int id)
{
return null;
}
}
It works neither I call:
/api/books/post1
nor
/api/books/post2
why and how to solve it?
UPDATE:
Problem is solved, problem was in simple types as parameters. I get 404 error
Message=No HTTP resource was found that matches the request URI 'http://localhost:37406/api/books/post1'.
with request:
POST http://localhost:37406/api/books/post1 HTTP/1.1
User-Agent: Fiddler
Host: localhost:35979
Content-Type: application/json; charset=utf-8
{
"str" : "Fffff"
}
and code:
[Route("Post1")]
[HttpPost]
public HttpResponseMessage Post1(string str)
{
return Request.CreateResponse();
}
[Route("Post2")]
[HttpPost]
public HttpResponseMessage Post2(int id)
{
return Request.CreateResponse();
}
but it works fine with complex type:
[HttpPost]
[Route("Post1")]
public HttpResponseMessage Post1(Book book)
{
return Request.CreateResponse();
}
[HttpPost]
[Route("Post2")]
public HttpResponseMessage Post2(Book book)
{
return Request.CreateResponse();
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Genre { get; set; }
}
Thank you Nkosi
UPDATE 2:
but it works when parameter is marked with [FromBody]
[Route("Post1")]
[HttpPost]
public HttpResponseMessage Post1([FromBody]string str)
{
return Request.CreateResponse();
}
[Route("Post2")]
[HttpPost]
public HttpResponseMessage Post2([FromBody]int id)
{
return Request.CreateResponse();
}
(for complex types it's unnecessary). Logically, but Route error confused :)