Web Api Controller not resolving action - asp.net-web-api

I am using .NET Core 2.2 and I have the controller below
[Route("api/[controller]")]
[ApiController]
public class CarsController : ControllerBase
{
[HttpPost]
[Route("api/cars/search")]
[ActionName("search")]
public ActionResult<IEnumerable<string>> SearchForCar([FromBody] SearchCriteria searchCriteria)
{
return new string[] { "value1", "value2" };
}
}
I am new to pure web api controllers.
I am confused about why when I post json to
http://localhost:51285/api/cars/search
I get 405 method not allowed?
I would normally have a route of
[Route("api/[controller]/action")]
That does work (once I remove route from the method attributes), but this wasn't the default provided in the template
Could someone let me know what I am missing?
Am I breaking convention by changing to
[Route("api/[controller]/[action]")]
Cheers
Paul

Since you not using the root slash in your action "/", the MVC middleware will search concatenating the route for controller and the action, should work like this
[Route("/api/[controller]/[action]")] // Check the root slash as first character
public ActionResult<IEnumerable<string>> SearchForCar([FromBody]
SearchCriteria searchCriteria)
Or like this
[Route("api/[controller]/[action]")] [ApiController] public class
CarsController : ControllerBase
Or
In controller:
[Route("api/[controller]")] [ApiController] public class
CarsController : ControllerBase
In action:
[Route("search")] // [action] Takes the method name
public <ActionResult<IEnumerable<string>>
SearchForCar([FromBody] SearchCriteria searchCriteria)

Related

FormatAttribute needs forward slash for action without parameter

I have a GET method without parameter and want below to work
/api/books.xml
This however works with forward slash
/api/books/.xml
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
[HttpGet]
[Route(".{format}")]
[FormatFilter]
public ActionResult<List<Book>> Get()
{
return bookService.Get();
}
}
Possible solutions that I tried are
Annotating without {id}
[Route("[controller]/[action].{format}")] // no slash between [action] and .{format}
Adding a default route in Startup.cs without {id}, so that if id parameter is not passed like in this problem then the routing should not expect a slash after {action}.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}");
});
Based on the currently defined routes on the controller, what you describe is by design.
Consider changing the routes to match the desired URL format
[ApiController]
public class BooksController : ControllerBase {
[HttpGet]
[Route("api/[controller].{format}")] //<--- GET api/books.xml
[FormatFilter]
public ActionResult<List<Book>> Get() {
return bookService.Get();
}
}

ASP.NET Web Api attribute routing and query string

I've specified my routing like this:
[RoutePrefix("users")]
public class UsersController : ApiController
{
[ResponseType(typeof(List<User>))]
[Route("")]
public IHttpActionResult GetAll()
{
}
[Route("{birthdate}")]
[ResponseType(typeof(List<User>))]
public IHttpActionResult GetByBirthdate(DateTime birthdate)
{
}
But when I am using this url: localhost/Users?birthdate=1907-04-19&api-version=2.0
I get redirected to GetAll() method. Why is that?
localhost/Users?birthdate=1907-04-19&api-version=2.0
that mean you call url users with param birthdate
If you want to go to second you need use
http://localhost/users/birthdate?birthdate=1907-04-19

Ajax not working after deploying to Azure

I am developing a web application using ASP.NET MVC Core. Everything works perfect on my local machine but whenever I deploy to Azure the Ajax calls always get a 404 Not Found.
Here's a snippet of one controller method:
[HttpGet]
public JsonResult GetPublicHolidays()
{
var events = adminService.GetPublicHolidays();
return new JsonResult(events);
}
And here's the Ajax call:
$.getJSON('#Url.Action("GetPublicHolidays","Admin")',
By default, the URL to an action in an ASP.NET Controller is not the name of the method. There's a lot going on by convention in ASP.NET.
As an example, this is a default ASP.NET Core API controller:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
As you can see in the comment, the route is <baseUrl>/api/values. This route is comprised of the base URL, the api prefix and the name of the controller. Because you add a HttpGetAttribute, ASP.NET knows that is the Get method.
So, considering this controller:
public class RandomController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<string>> WhateverWeirdMethodName()
{
return new string[] { "value1", "value2" };
}
}
The URL for the GET request would be <baseUrl>/api/random

How do I add API Endpoints in ASP.NET?

I would like to register API Endpoints in ASP.NET by just adding few methods in ApiController. A new method there means a new API.
In a random example below:
public class ProductController : ApiController
needs to serve the following Endpoints:
/
/price
/price/discount
Problem here is all endpoints are having a GET request to /, and result in same output as /.
Reference URL and Service Contract
You can place Route annotation at method for which you want to use custom route.
public class CustomersController : ApiController
{
// this will be called on GET /Customers or api/Customers can't remember what default
//config is
public List<Customer> GetCustomers()
{
...
}
// this will be called on GET /My/Route/Customers
[HttpGet, Route("My/Route/Customers)]
public List<Customer> GetCustomersFromMyRoute()
{
...
}
}

Attribute routing and inheritance

I am playing around with the idea of having a base controller that uses a generic repository to provide the basic CRUD methods for my API controllers so that I don't have to duplicate the same basic code in each new controller. But am running into problems with the routing attribute being recognized when it's in the base controller. To show exactly what the problem I'm having I've created a really simple WebAPI controller.
When I have a Get method in the main Controller and it inherits from the ApiController directly I don't have any problems and this works as expected.
[RoutePrefix("admin/test")]
public class TestController : ApiController
{
[Route("{id:int:min(1)}")]
public string Get(int id)
{
return "Success";
}
}
When I move the Get method into a base controller it is returning the contents of the 404 page.
[RoutePrefix("admin/test")]
public class TestController : TestBaseController
{
}
public class TestBaseController : ApiController
{
[Route("{id:int:min(1)}")]
public string Get(int id)
{
return "Success";
}
}
Some more interesting notes:
I can access the action at GET /Test/1. So it is finding it based on the default route still.
When I try to access POST /admin/test, it returns the following JSON
{
"Message":"No HTTP resource was found that matches the request URI 'http://test.com/admin/test'.",
"MessageDetail":"No type was found that matches the controller named 'admin'."
}
Does anyone know of a way to get the routing to work with attributes from a base controller?
Attribute routes cannot be inherited. This was a deliberate design decision. We didn't feel right and didn't see valid scenarios where it would make sense to inherit them.
Could you give a more realistic scenario as to where you would want to use this?
[Update(3/24/2014)]
In the upcoming 5.2 release of MVC Web API, there is going to be an extensibility point called System.Web.Http.Routing.IDirectRouteProvider through which you can enable the inheritance scenario that you are looking for here. You could try this yourself using the latest night builds(documentation on how to use night builds is here)
[Update(7/31/2014)]
Example of how this can be done in Web API 2.2 release:
config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());
//---------
public class CustomDirectRouteProvider : DefaultDirectRouteProvider
{
protected override IReadOnlyList<IDirectRouteFactory>
GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
{
// inherit route attributes decorated on base class controller's actions
return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>
(inherit: true);
}
}
Using Web API 2.2, you can:
public class BaseController : ApiController
{
[Route("{id:int}")]
public string Get(int id)
{
return "Success:" + id;
}
}
[RoutePrefix("api/values")]
public class ValuesController : BaseController
{
}
config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());
public class CustomDirectRouteProvider : DefaultDirectRouteProvider
{
protected override IReadOnlyList<IDirectRouteFactory>
GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
{
return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>
(inherit: true);
}
}
as outlined here: http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22
Got it.
[Route("api/baseuploader/{action}")]
public abstract class BaseUploaderController : ApiController
{
[HttpGet]
public string UploadFile()
{
return "UploadFile";
}
}
[Route("api/values/{action}")]
public class ValuesController : BaseUploaderController
{
[HttpGet]
public string Get(int id)
{
return "value";
}
}
One caveat here is that the route action paramter must be the same as the action name. I could not find a way to get around that. (You cannot rename the route with a RouteAttribute)

Resources