Home > front end >  How to use MapControllers on a sub path?
How to use MapControllers on a sub path?

Time:12-20

I have an application which uses the Uno platform for a UI and I want to have an additional REST API for it to communicate.

Right now, when I have a controller like:

[ApiController]
[Route("[controller]")]
public class AwesomeController: ControllerBase {
  ...
}

the

app.MapControllers();

installs this as https://mycompany.com/awesome

How do I install all my controllers to a subpath, like: https://mycompany.com/api/awesome without putting the api/ bit in every [Route] attribute?

CodePudding user response:

Try to register the following conventional-route in the Program.cs:

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "api/{controller=Awesome}/{action?}/{id?}");

app.MapControllers();
app.Run();

After registering this route remove the route attributes in the controller class:

//[ApiController]
//[Route("[controller]")]
public class AwesomeController: ControllerBase {
  ...
}

Now you can use:

https://mycompany.com/api/awesome  

or

https://mycompany.com/api/another_controller  
  • Related