简体   繁体   中英

Redirect to action in area actions

I have an area which has a controller with some actions.

the controller name is home .

the action which has the problem looks like below:

 public IActionResult Action1()
 {
         some code ...

        return RedirectToAction("Action2");
 }

Action2 looks like:

 public IActionResult Action2()
 {
         some code ...

        return View();
 }

the problem is that it redirects to the mentioned action but it doesn't write the area name before the controller name

url should be => MyArea/home/action2

but it is => home/action2

which makes an 500 error.

and my startup is:

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

            endpoints.MapAreaControllerRoute(
                  name: "areas",
                         areaName: "MyArea",
                         pattern: "{area=MyArea}/{controller=Home}/{action=Index}/{id?}"
                );
        });

does any have any solution?

thanks in advance.

1 - Change RedirectToAction to

return RedirectToAction("Action2", "Home", new { area = "MyArea" });

2 - Your route configuration must be like this and you must register area before default controller

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "MyArea",// or name: "areas",
        pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute(
         name: "default",
         pattern: "{controller=Home}/{action=Index}/{id?}");
});

3 - On the top of the controller you must add [Area("MyArea")] attribute

[Area("MyArea")]
public class HomeController : Controller
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM