ASP.NET Web API method for both GET and POST - asp.net-web-api

I have the following method in my API:
[HttpGet]
public HttpResponseMessage ExecuteCommand()
{
// logic
}
This method currently serves only the http GET method. I would also like it to respond to http POST method - Is that possible? or do I have to duplicate the method?
Thanks

You can do it like this
[AcceptVerbs("Get", "Post")]
public HttpResponseMessage ExecuteCommand()
{
// logic
}
This is possible since the constructor looks like this, and takes an array of strings.
public AcceptVerbsAttribute(
params string[] verbs
)

Related

MVC Request did not match any routes

I have following controller where I need to find routes for various actions:
[Route("api/[controller]/[action]")]
[EnableCors("MyPolicy")]
public class UserController : Controller
{
IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[HttpGet]
public async Task<IEnumerable<User>> Get()
{
return await _userService.GetAllAsync();
}
[HttpGet("{id}")]
public async Task<User> Get(object id)
{
return await _userService.FirstOrDefaultAsync(x => x.Id == (ObjectId)id);
}
}
According to https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
such request http://localhost:55556/User/Get should be passed to a route but I get the following message when running in Visual Studio debug:
Request starting HTTP/1.1 GET http://localhost:55556/User/Get
dbug: Microsoft.AspNetCore.Builder.RouterMiddleware[1]
Request did not match any routes.
What could be wrong here? Is there any way to list all possible routes? Or make sure what controllers are registered?
Look on your route template definition more carefully:
[Route("api/[controller]/[action]")]
It has a api/ string prefix (const) and so MVC middleware experts requests like
http://localhost:55556/api/User/Get
not
http://localhost:55556/User/Get
Also, if talking in the scope of REST, it is a bad idea to use routes like User/GET, User/POST etc. For such purpose, the corresponding HTTP Method (Gey, Post, Put, ...) is defined and used. In other words, you have a redundant duplication right now, as a request, for example, from curl looks like:
curl -X GET 'http://localhost:55556/User/Get`

web api 2 controller multiple post methods

I have a controller with the default post method. I want to add one more with a different name and action. The problem is when I make the request POST (http://localhost:57926/api/Users/Login) it doesn't execute Login method, it executes the default PostUser method.
How can I fix this?
// POST: api/Users
[ResponseType(typeof(User))]
public IHttpActionResult PostUser(User user){
//Some code
}
[HttpPost]
[Route("Login")]
public IHttpActionResult Login(JObject form)
{
//some code
}

When writing Web Api method in .Net is it necessary to have the method name prefix with HTTP code like GET, Post etc?

When writing Web Api method in .Net is it necessary to have the method name prefix with HTTP code like GET, POST etc?
Example:
public IEnumerable<Product> GetAllProducts();
public IHttpActionResult GetProduct(int id);
public IHttpActionResult PostProduct(Product prod);
No, it's not necessary, but it's one of several conventions to map HTTP verbs to action methods. You could, for example, do this:
[HttpGet]
public IHttpActionResult AllProducts();
or this:
public IHttpActionResult GetAllProducts();
and they would both handle GET requests.
If you utilise attribute routing you don't need to.
Have a read of the docs
eg:
The following example maps the CreateBook method to HTTP POST requests.
[Route("api/books")]
[HttpPost]
public HttpResponseMessage CreateBook(Book book) { ... }

web api controller action methods

I am trying to get a web api call to work: I want to submit an email address and then on the server, the method will validate and return null or a message.
This is what I tried:
[Post]
public string validate(string email) {
return this._contextProvider.ValidateEmail(email);
}
However, I get this message returned to the client: No HTTP resource was found that matches the request URI 'https://localhost:44300/breeze/data/validate
The payload looks like this: {email: "Greg#gmail.com"}
The problem, it turns out, was the parameter binding.
In the Web API, binding is handling differently than MVC. By default, simple types are extracted from the URI, not the body. Complex types are extracted from the body of the message.
I then added the [FromBody] Attribute to the Action Method, and it then found the action method. But alas, the email parameter was null.
public string validate([FromBody]string email) {
return this._contextProvider.ValidateEmail(email);
}
Turns out when using this trick, the body must NOT be json, but constructed like a querystring - email=greg#gmail.com. I didn't want do do that, so ended up creating a class to accept the parameter, and that worked as expected.
public class ParameterizedAction {
public string Parameter { get; set; }
}
public string validate(ParameterizedAction arg) {
return this._contextProvider.ValidateEmail(arg.Parameter);
}
This article has more info: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
as well as this one: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

What advantage do we get if we specify Frombody and FromUri attribute in web api?

What are the benefits/advantages we get if we specify this frombody and fromuri attribute in web-api?
Web API parameter binding expects simple type values coming from query string, and complex types like array coming from the body of the request. Hence if you have an action method like this one:
public class EmployeesController : ApiController
{
public IHttpActionResult Get(int id, string[] names)
{
return Ok("Method Called");
}
}
,and if you want to formulate your request like this:
/api/employees?id=1&names=Fred&names=Anna
, then without [FromUri] the value of "names" parameter won't be bound.
So your API method must be like this in order to get all parameters bound:
public IHttpActionResult Get(int id,[FromUri] string[] names)
{
return Ok("Method Called");
}
More from here: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Resources