How to redirect url to specific endpoint

I need to add an api endpoint in a web project (=> WebSiteUrl/api/token).

The problem is that this project has already a basic controller called “ApiController” with multiple actions. I can’t use this controller because it is a basic Controller and not an ApiController.

Is there a way to set the WebSiteUrl/api/token endpoint, despite the fact that there is already a controller that is using the route WebSiteUrl/api/actions ?

I already created an apicontroller that is using the following route : WebSiteUrl/api/controller/action

Thanks for any help !

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Normal MVC controller implements Controller, If you want to create an API controller you have to create a controller which will implement ControllerBase abstract class.

For example an API controller will look like,

[Route("api/[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
    [HttpGet('getall')]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
    .......
}

We can configure the routing from the [Route()] attribute. Here is a convention of naming a controller, here in ‘ExampleController’ will be considered as ‘Example’ for the name of this controller.

So, according to the route attribute( [Route("api/[controller]")] ) the path will be “websiteUrl/api/example”. [controller] tag will match any controller name. So if you rename this controller from ExampleController to TestController(You have to concat “Controller” for controller naming that is how the system will recognize it) the path will be “websieUrl/api/test” for this controller. Otherwise you can hard coded the route as [Route("api/example")], this way it won’t depend on controller name.

for your requirement you can do,

[Route("api/token")]
[ApiController]
public class ExampleController : ControllerBase
{
    // GET: api/token/
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

so, if you run a get request to “websiteUrl/api/token” it will point to this,

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

and if want to redirect the url to your desired path, then go to launchsettings.json on your project and if you are using IISExpress then in the json file inside profiles–>IISExpress set “”launchUrl”: “”


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x