Home > other >  why does RedirectToAction("Index") in HomeController, go to "/Index" instead of
why does RedirectToAction("Index") in HomeController, go to "/Index" instead of

Time:03-31

Program.cs contains the following (put there by the default project template):

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

HomeController.cs contains:

    [HttpPost]
    public async Task<IActionResult> Login(LoginModel model)
    {
        return RedirectToAction("Index");
    }

return RedirectToAction("Index"), causes "/Index" to load instead of "/Home/Index". Can anyone explain?

I'm unable to understand why this would happen, according to the documentation:

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0

EDIT:

Technically I have a Blazor Index.razor page at /Index, that loads instead of my Index.cshtml view at /Home/Index. So i'm really seeing a different page.

CodePudding user response:

From what I understand, and I admit I am having a hard time finding the official documentation for it that says it this plainly, is that this is filling in defaults:

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

What it is saying is that if there is no controller or action, use HomeController as the controller and index as the action. If Id is included, just add it as a parameter to the previous controller and action listed.

CodePudding user response:

You want to use the following:

RedirectToAction("Index", "Home");

According to the following documentation.

Starting here on GitHub, it looks like it just builds a URL based on the provided values. So omitting the controller name, the route will not be fully built. Since this is a string based constructor, the method does not know what you are actually targeting.

  • Related