Controller route attribute only relevant for root function? - c#

I have a question about .NET Core controller routing. Recently I discovered that the controller route attribute (which you place just above the controller) only works for the root method, or at least it seems that way.
My code:
using KrabbelMicroservice.Models;
using KrabbelMicroservice.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
namespace KrabbelMicroservice.Controllers;
[ApiController]
[Route("/profile")] // <-- This is the controller routing attribute I am talking about
public class ProfileKrabbelController : Controller
{
private readonly IProfileKrabbelService _krabbelService;
public ProfileKrabbelController(IProfileKrabbelService krabbelService)
{
_krabbelService = krabbelService;
}
[HttpGet]
public IActionResult Index()
{
// not relevant
}
[HttpGet]
[Route("/id/{krabbelId}")]
public IActionResult GetKrabbelById(long krabbelId)
{
// not relevant
}
[HttpGet]
[Route("/pid/to/{profileId}")]
public IActionResult GetKrabbelsToProfileId(long profileId)
{
// not relevant
}
[HttpGet]
[Route("/pid/from/{profileId}")]
public IActionResult GetKrabbelsFromProfileId(long profileId)
{
// not relevant
}
[HttpGet]
[Route("/pid/with/{profileId}")]
public IActionResult GetKrabbelsWithProfileId(long profileId)
{
// not relevant
}
[HttpPost]
[Route("/new")]
public IActionResult AddKrabbel(ProfileKrabbel krabbel)
{
// not relevant
}
[HttpPut]
[Route("/update")]
public IActionResult UpdateKrabbel(ProfileKrabbel krabbel)
{
// not relevant
}
[HttpDelete]
[Route("/delete")]
public IActionResult DeleteKrabbel(ProfileKrabbel krabbel)
{
// not relevant
}
}
In my swagger launch the requests look like this:
I expected that all paths would be prefixed by /profile/ but it seems like only the root function (which did not have its own route attribute) implemented the prefix.
I am not only trying to get a fix for this, but also looking for an explanation as to why my controller route attribute is ignored for the other requests. The only possibility I can think of is the specific route attributes for each endpoint overriding the controller route attribute but I would like to hear it from an expert.
Secondly I would of course also like to find a solution to this problem, preferrably not adding /profile before every seperate route but if that is the only solution so be it.
Thanks in advance!

you should be remove "/" if you have root route
ex:
[Route("test")]
[ApiController]
public class TestController3 : Controller
{
[HttpGet]
[Route("testobj")]
public TestObj Test()
{
return "test";
}
}
the even shorter in httpget
[HttpGet("testobj")]
the both output:
test/testobj

Related

.NET 6 best way to differentiate a route in the same controller class

I have an API controller say TestController.
I have the following route definition: api/[controller] on class level and I can call the default get method as follows: .../api/test
I want to have another method in the same controller, I also want to call it with Get and the link should be as follows: .../api/test-abc
What is the best way to differentiate this second method within the same controller class.
For test-abc, you can configure the Route attribute as ~/api/test-abc to override the controller base route. See this link for details.
[Route("api/[controller]")]
public class TestController : ControllerBase
{
public IActionResult Get()
{
// ...
}
[HttpGet]
[Route("~/api/test-abc")]
public IActionResult GetAbc()
{
// ...
}
}
This approach changes only the URL of the "test-abc"-action; all other actions of the controller use the base URL configured on class level.
In .Net 6 by following Minimal API's
app.MapGet("api/test", () =>
{
return "";
});
app.MapGet("api/test-abc", () =>
{
return "";
});
By following Traditional Method
[Route("api")]
public class TestController : ControllerBase
{
[HttpGet("test")]
public IActionResult Get()
{
// ...
return Ok();
}
[HttpGet("test-abc")]
public IActionResult GetAbc()
{
// ...
return Ok();
}
}
You can by defining the controllers route template like as below:
[Route("api/[controller]")]
public class TestController : Controller
{
...
}
So you can define a method like:
[HttpGet]
[Route("~/api/Test/Index")]
public IActionResult Index()
{
return Foo.Bar();
}
[HttpGet]
[Route("~/api/Test/Index2")]
public IActionResult Index2()
{
return Foo.Bar2();
}
[HttpGet]
public IActionResult Index3()
{
return Foo.Bar3();
}
You can call it by ../api/test/index2 to use the method Index2 or ../api/test to use Index3.
This is for the standardized way to do, in your case you would use - instead of / at the Route("...") attribute.
If you use - you need to call ../api/test-index2
For further information take a look at documentation.

ASP.NET Core routing engine confusion

I am trying to create a solid example of exactly how the ASP.NET Core routing engine works and I was surprised by the results.
The premise behind this example is hitting a controllers index page, and then using AJAX requests to load data.
I created a ASP.Net Core application with MVC. Then I added the following Controller:
namespace WebApplication2.Controllers {
using Microsoft.AspNetCore.Mvc;
public class SearchController : Controller {
public IActionResult Index() {
return View();
}
[HttpGet("{company}")]
public IActionResult Get(string company) {
return Ok($"company: {company}");
}
[HttpGet("{country}/{program}")]
public IActionResult Get(string country, string program) {
return Ok($"country: {country} program: {program}");
}
}
}
I also create a simple View to go along with Index with the words "Search Page" so that you can see it get called.
The problem is that the routes that are created from this don't make sense.
Expected Results
/Search/Index
/Search/{company}
/Search/{country}/{program}
Using Company: "Abc", Country: "Canada" and Program: "Plumbing" as an example:
/Search/Index
Produces: "Search Page"
/Search/Abc
Produces "company: Abc"
/Search/Canada/Plumbing
Produces: "country: Canada program: Plumbing"
Actual Results
However it doesn't work like this at all. Instead these are the results:
/Search/Index
Produces: "country: Search program: Index"
/Search/Abc
Produces: "country: Search program: Abc"
/Search/Canada/Plumbing
Produces: 404 Not Found
Clearly the route for Index and Get string company are confused, and it is treating the Controller name as a parameter.
I can make it work with the following code, but I thought the routing engine would produce the same results:
public class SearchController : Controller {
public IActionResult Index() {
return View();
}
[HttpGet("[controller]/{company}")]
public IActionResult Get(string company) {
return Ok($"company: {company}");
}
[HttpGet("[controller]/{country}/{program}")]
public IActionResult Get(string country, string program) {
return Ok($"country: {country} program: {program}");
}
What is wrong with my understanding? It seems silly to have to specify [controller] explicitly.
You have mixed the conventional routing and the attribute routing while you should not do that.
For your original code, it will work when you remove all the /Search in your url.
To use the controller name, you need to set [Route("[controller]")] on your mvc controller to make your url work as expected.
[Route("[controller]")]
public class SearchController : Controller
{
[HttpGet("[action]")]
public IActionResult Index()
{
return View();
}
[HttpGet("{company}")]
public IActionResult Get(string company)
{
return Ok($"company: {company}");
}
[HttpGet("{country}/{program}")]
public IActionResult Get(string country, string program)
{
return Ok($"country: {country} program: {program}");
}
}
Specify the root route above your class
[Route("Search")]
public class SearchController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet("{company}")]
public IActionResult Get(string company)
{
return Ok($"company: {company}");
}
[HttpGet("{country}/{program}")]
public IActionResult Get(string country, string program)
{
return Ok($"country: {country} program: {program}");
}
}
Routing is responsible for mapping request URL to an endpoint and it comes with two types of Conventional and Attributes routing.
And from your question, you are expecting conventional routing with default route which you can achieve in .NET CORE using below line of code.
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Search}/{action}/{id?}");
});
Note: But keep in mind that conventional routing will not work if you decorate your controller with [ApiController] attribute.
By default .NET CORE supports attribute routing so you have to prefix the route by placing the [Route] attribute on the controller level. Please see the below example
[Route("api/[controller]")]
[ApiController]
public class SearchController : ControllerBase
{
[HttpGet("{company}")]
public IActionResult Get(string company) {
return Ok($"company: {company}");
}
[HttpGet("{country}/{program}")]
public IActionResult Get(string country, string program) {
return Ok($"country: {country} program: {program}");
}
}
The above code will work as you expected.
If you are decorating your controller by [ApiController] attribute then you have to use Attribute routing and any conventional routing defined in startup class will be overridden. Please see more details here.

ASP.NET Core Attribute routing

I am migrating a project to asp net core, but I could not configure these routes, i am using attributes to map actions.
Code for ASP.Net WebAPI2
[Route("api/[controller]")]
public class SalesController : Controller
{
// api/sales/1 -> ok
[HttpGet]
public HttpResponseMessage Get(int id)
{
// Logic
}
// api/sales -> ok
[HttpGet]
public HttpResponseMessage Get([FromUri] PaginationHelper pagination)
{
// Logic
}
// api/sales?me -> ok
[ActionName("Get")]
public HttpResponseMessage GetMe(bool? me)
{
// Logic
}
}
Code for ASP.Net Core
In the file Startup.cs is set app.UseMvc();
[Route("api/[controller]")]
public class SalesController : Controller
{
// api/sales/1 -> ok
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// Logic
}
// api/sales -> don't work
[HttpGet] // -> ???
public IActionResult Get(PaginationHelper pagination)
{
// Logic
}
// api/sales?me -> don't work
[HttpGet] // -> ???
public IActionResult GetMe(bool? me)
{
// Logic
}
}
Maybe I'm too late to this discussion, but this could be valuable to other people who end up reading this page, like I did. The problem with your API endpoints is that you configured 2 of them to handle the same route: GET /api/sales.
If you try to access that route, the framework won't be able to distinguish between Get(PaginationHelper) and GetMe(bool?). The reason why is that they both have [HttpGet] attribute, which means that both are capable of handling the route you specified in the [Route("api/[controller]")] attribute, just above your class declaration. Since those are declared as capable of handling that same route, hence your Exception (Multiple actions matched).
The solution for your problem depends on which action you want to handle that ambiguous route. Assuming that you want the route GET /api/sales to be handled by Get(PaginationHelper), you can change the GetMe(bool?) action method and its [HttpGet] attribute to something like this:
[HttpGet("me")] // GET api/sales/me
public IActionResult GetMe() {
// Logic
}
The new framework expects a more explicit indication of the intent of the endpoint.
[Route("api/[controller]")]
public class SalesController : Controller {
[HttpGet("{id:int}")] // GET api/sales/1
public IActionResult Get(int id) {
// Logic
}
[HttpGet] // GET api/sales?page=1 assuming PaginationHelper has page property
public IActionResult Get([FromQuery]PaginationHelper pagination) {
// Logic
}
[HttpGet] // GET api/sales?me=true
public IActionResult GetMe(bool? me = false) {
// Logic
}
}
Reference Asp.Net Core: Model Binding

Route Prefix VS Controller Name ( Web api )

I was wondering that if we use RoutePrefix attribute in our web api controller with a different name from controller's actual name. So would it work or not?
As far as i did
[RouterPrefix("quotation")]
public class SaleOrderController : ApiController { ... }
if we define RoutePrefix like above we can't access it via /quotation but we can access it using saleorder.
So what is RoutePrefix for or am i doing something wrong ?
To use default route use Route("")
[RoutePrefix("quotation")]
public class SaleOrderController : ApiController {
//GET quotation
[Route("")]
[HttpGet]
public IHttpActionResult GetAll() { ... }
}
Source: Attribute Routing in ASP.NET Web API 2 : Route Prefix
In order for it to work, you need to call the code below inside your WebApiConfig.Register() method:
config.MapHttpAttributeRoutes();
So your RoutePrefix works as exptected:
[RoutePrefix("quotation")]
public class SaleOrderController : ApiController
{
[Route("example")]
[HttpGet]
public IHttpActionResult Example()
{
return Ok();
}
[Route("another")]
[HttpGet]
public IHttpActionResult Another()
{
return Ok();
}
}
So your could access your apis like this:
quotation/example
quotation/another

Creating a different route to a specific action

I am working on an asp.net 5 mvc api, and I am currently working on the Accounts Controller.
since I saw in many different places that there is a convention of using /api/Tokenrouting to a login in a web api. I would like to route to that specific method without the accounts prefix, I would prefer not using a different controller, and I would prefer using Attributes over routing in Startup.cs to avoid confusion in the future.
this is what I have currently
[Route("api/[controller]")]
public class AccountsController : Controller
{
[HttpPost("login")]
public async Task<JwtToken> Token([FromBody]Credentials credentials)
{
...
}
[HttpPost]
public async Task CreateUser([FromBody] userDto)
{
...
}
}
With attribute routing you can use a tilde (~) on the Action's route attribute to override the default route of the Controller if needed:
[Route("api/[controller]")]
public class AccountsController : Controller {
[HttpPost]
[Route("~/api/token")] //routes to `/api/token`
public async Task<JwtToken> Token([FromBody]Credentials credentials) {
...
}
[HttpPost]
[Route("users")] // routes to `/api/accounts/users`
public async Task CreateUser([FromBody] userDto) {
...
}
}
For ASP.NET Core it seems that the tilde ~ symbol (see accepted answer) is not needed anymore to override the controller's route prefix – instead, the following rule applies:
Route templates applied to an action that begin with a / don't get combined with route templates applied to the controller. This example matches a set of URL paths similar to the default route.
Here is an example:
[Route("foo")]
public class FooController : Controller
{
[Route("bar")] // combined with "foo" to map to route "/foo/bar"
public IActionResult Bar()
{
// ...
}
[Route("/hello/world")] // not combined; maps to route "/hello/world"
public IActionResult HelloWorld()
{
}
}
from https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
[Route("[controller]/[action]")]
public class HomeController : Controller
{
[Route("~/")]
[Route("/Home")]
[Route("~/Home/Index")]
public IActionResult Index()
{
return ControllerContext.MyDisplayRouteInfo();
}
public IActionResult About()
{
return ControllerContext.MyDisplayRouteInfo();
}
}
In the preceding code, the Index method templates must prepend / or ~/ to the route templates. Route templates applied to an action that begin with / or ~/ don't get combined with route templates applied to the controller.

Categories

Resources