MVC trying to do a Get request - c#

I am trying to do a GET request on MVC 4.0 (WebServiceREST) that some method use POST and other use GET but I cant make it works
I used [System.Web.Mvc.AcceptVerbs(HttpVerbs.Get)] but It didnt work still getting "The requested resource does not support the HTTP 'GET' method"
My Controller:
public class RecuperarDatosAppController : ApiController
{
#region RecuperarClasesColectivas
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Get)]
[ResponseType(typeof(List<ActividadesColectivas>))]
public IHttpActionResult RecuperarClasesColectivas(short idInstalacion, string secretKey = "NOSECRETKEY")
{
BsSecurity bSecurity = new BsSecurity(BsSecurity.Tipo.Publica);
if (bSecurity.comprobar(secretKey))
{
BsActividadesColectivas bsActividades = new BsActividadesColectivas();
return Ok(bsActividades.GetActividadesColectivas(idInstalacion));
}
return NotFound();
}
#endregion
}

Though you state this is MVC and tagged it as such, it's actually Web API, because you're inheriting from ApiController. So you should decorate the method with the [HttpGet] attribute from the System.Web.Http namespace. Note that renaming it to have Get prepended like Yoink is suggesting isn't necessary, although that is the common convention.

I believe you need to prepend "Get" to methods that you wish to expose by by GET requests.
So try GetRecuperarClasesColectivas instead of RecuperarClasesColectivas.
You'll still call it by /api/RecuperarClasesColectivas/id for example, the routing just needs the "Get" part adding.

Related

MVC Attribute Routing with query parameter not working

I am trying to combine my UI project and WebAPI project into one to make it more maintainable, however I am getting an error with the routing as below:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:64182/api/v1/business?id=101'.",
"MessageDetail": "No type was found that matches the controller named 'api'."
}
I have added attribute routing on the method to get it to work, but it only works with the following url:
MVC ACtion:
[HttpGet, Route("api/v1/business/{id:int}")]
public IHttpActionResult Get([FromUri]int? id)
{
....
}
http://localhost:64182/api/v1/business/101
The intended url signature cannot change and it should still use the query parameter:
http://localhost:64182/api/v1/business?id=101
In the Route attribute, I cannot add a question mark because it is not allowed.
The system is already being used by many users and I cannot change the signature unfortunately otherwise this would break their systems.
How can I get this to work or what Route template can I use to include the query parameter?
I think the attribute [FromUri] is deprecated. Try using [FromRoute]. Also, I would structure my routing from the controller class.
The following is for http://localhost:64182/api/v1/business/101
[Route("api/v1/[controller]")]
[ApiController]
public class Business : ControllerBase
{
[HttpGet("/{id:int}")]
public async Task<ActionResult<YourBusinessDto>> Get([FromRoute] int id)
{
//Your code to get your business dto here.
}
}
The following is for http://localhost:64182/api/v1/business?id=101
[Route("api/v1/[controller]")]
[ApiController]
public class Business : ControllerBase
{
[HttpGet]
public async Task<ActionResult<YourBusinessDto>> Get([FromQuery] int id)
{
//Your code to get your business dto here.
}
}
In our order collection, each order has a unique identifier. We can go to the collection and request it by "id". Typical RESTful best practice, this can be retrieved by its route, for example "api/orders/1"
//api/orders/1
[HttpGet("api/orders/{id}")]
public string test1([FromRoute]int id)
{
return "test1";
}
This attribute will instruct the ASP.NET Core framework to treat this operation as a handler for the HTTP GET verb and handle routing. We provide an endpoint template as an attribute parameter. This template is used as the route that the framework will use to match incoming requests. In this template, the {id}​​ value corresponds to the route part as the "id" parameter. The FromRoute attribute tells the framework to look up the "id" value in the route (URL) and provide it as the id parameter.
In addition, we can easily write it to use the FromQuery property. This then instructs the framework to predict a query string with an "identifier" name and corresponding integer value. Then pass the value as the id parameter to the operation. Everything else is the same.
However, the most common method is the aforementioned FromRoute usage-where the identifier is part of the URI
//api/orders?id=1
[HttpGet("api/v1")]
public string test2([FromQuery]int id)
{
return "test2";
}
In addition, you can refer to this detailed article for more attribute usage, which may be helpful to you:
https://www.dotnetcurry.com/aspnet/1390/aspnet-core-web-api-attributes

WebApi 2 POST Method returns "Multiple actions were found that match the request"

My simple web api application keeps returning "500 Internal Server Error" with the message "Multiple actions were found that match the request" and I thought this must be a routing problem.
Here is a gist with the UserController and the WebApiConfig files that can have an impact on this issue.
I went with the web api convention when I created my methods and I don't want to use attributes on the methods to specify type and route.
If I use a Route attribute on the POST method, it will work, but it doesn't make sense to me why it doesn't work w/o that attribute since I use the naming convention for a POST method.
ex that works:
[Route("api/user")]
public IHttpActionResult Post([FromBody]User user)
{
if (!ModelState.IsValid)
{
return BadRequest("Model state not valid!");
}
if (db.Users.ToList().Any(u => u.Username.ToLowerInvariant().Equals(user.Username.ToLowerInvariant())))
{
return BadRequest("Username already exists in the database!");
}
db.Users.Add(user);
db.SaveChanges();
return Ok($"Added user {user.Username}");
}
Any thought is welcomed.
Clearly the problem is with your Dispose() method. This method is conflicting with your Post() action and WebAPI action selector can't decide which action to choose.
Just make Dispose() public to protected.

ASP.NET WebAPI multiple actions were found

I have a web api controller and two GET methods:
public class ImagesController : ApiController {
[HttpGet]
public HttpResponseMessage GetImages() { }
[HttpGet]
public HttpResponseMessage Download([FromUri]int[] ids) { }
}
Why I'm getting multiple actions found error, when trying to reach /api/Images, why both actions are the same?
When you created controller, you have assigned HttpGet to two different methods. Making that you have confused web server when it tries to process your request. Since you are sending GET verb to the controller it self, instead directly to the method, web server can not determinate what method should be invoked.
You can try with /api/Images/GetImages in order to directly hit a method, or remove one of listed.
If you see the Web API feature it work for the selected httm methods like GET,PUT,POST,DELETE.
So if you create two action method with same name it will give error. To avoid this error you have to redefine the DefaultAPI path in route.config file.
Change it to
API/{controller}.....
After changing this acces your API from browser like
Or
Mark as a answer if this resolve your issue.

Using WebApi RoutePrefix attribute on a base controller

I would like all controllers which inherit from AdminBaseApiController to be prefixed with 'admin'.
This works fine of course:
[RoutePrefix("admin")]
public class ToggleController : AdminBaseApiController
{
[Route("toggle")]
public HttpResponseMessage Get()
{
}
}
However when I move the RoutePrefix("admin") out of the ToggleController and into the AdminBaseApiController (where I want it) - The route fails and I get a 404.
Am I looking at this all wrong? Thanks in advance!
Support for inheritance has been enabled in Web API 2.2 release...You can take a look at an example in the following Release Notes:
http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22#ARI

What is the advantage of adding the [HttpGet] annotation?

In the event that a Controller specifies a route:
[Route("api/platypus/getPlatypi")]
public List<Platypus> GetAllPlatypi()
{
return _platypusRepository.GetPlatypi();
}
...is there any advantage to annotating it with a "[HttpGet]" like so:
[HttpGet]
[Route("api/platypus/getPlatypi")]
public List<Platypus> GetAllPlatypi()
{
return _platypusRepository.GetPlatypi();
}
?
For the example you have given there is not any advantage to adding the HTTP method attribute. By convention Web API will try to match a controller method that starts with the HTTP request method (GET, POST, PUT etc.).
In your example the method GetAllPlatypi will be considered for a match for all GET requests to that controller.
If however your method was named FindAllPlatypi you would need to add the [HttpGet] attribute to make it clear that this method is meant for GET requests.

Categories