Search code examples
c#asp.net-coreroutesasp.net-mvc-routing

ASP.NET Core 3.0 change default endpoint route with attribute routing


App is on ASP.NET Core, we recently migrated to 3.0.

I need to navigate to mycontroller/login, so login action instead of default index action but struggle with changing the default controller action method. I keep getting my index page, only when I manually navigate to /login, I will get the page. Also as a convention thing I need to keep the attribute routing.

[Route("/mycontroller")]
    public class MyController : Controller
    {
       private readonly IAuthenticationService _authenticationService;

        public MyController(IAuthenticationService authenticationService)
        {

            _authenticationService = authenticationService;
        }

        [Route("login")]
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var user = await _authenticationService.PerformCheckAndLogin(model.UserName, model.Password);
                    if (user != null)
                    {
                        var userClaims = new List<Claim>

In my Configure method I tried:

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("default", "{controller=mycontroller}/{action=login}");
        });

Solution

  • Simple redirecting at the top of my Index action method did the work, after checking if the user is logged in or not redirect to login page.

    [HttpGet]
            public async Task<IActionResult> Index()
            {
                if (true)// implement cookie policy
                    return RedirectToAction("Login");