【问题标题】:Redirect to Area always gives 404 or wrong Redirect重定向到区域总是给出 404 或错误的重定向
【发布时间】:2016-08-19 10:12:55
【问题描述】:

我正在尝试制作一个应用程序,该应用程序的区域只有您登录后才能进入。

由于某种原因,当我在登录后重定向到我的区域时失败。导致以下Route生成

 var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
 if (result.Succeeded)
 {
    _logger.LogInformation(1, "User logged in.");
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
  }

重定向所做的路由: http://localhost:23490/Account/Login?ReturnUrl=%2FDashboard%2FHome

如果我直接浏览链接(像这样)http://localhost:23490/Dashboard/Home/Index

我得到一个 404

我试图访问的控制器是这样定义的

  //[Authorize]
[Area("Dashboard")]
[Route("Dashboard/[controller]")]
public class HomeController : Controller
{
    // GET: Dashboard
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

我检查了我能找到的有关此主题的所有内容,但由于这是非常新的,因此没有太多关于此的信息。

我尝试过的

  • 检查是否正确定义了视图和控制器,它们是
  • 检查路由是否正确,在我看来是这样

            app.UseMvc(routes =>
        {
            routes.MapRoute(name: "areaRoute",
                template: "{area:exists}/{controller=Home}/{action=Index}");
    
            routes.MapRoute(
                name: "default",
                template: "{controller=Route}/{action=Index}/{id?}");
        });
    
  • 尝试为操作创建自定义重定向(失败)

我希望有人能在这个话题上帮助我。 谢谢!

【问题讨论】:

  • 为什么在控制器上使用[Route("Dashboard/[controller]")]?你试过没有这个吗?
  • 不,我没有尝试这个,但我使用的设置是基于另一个 SO 问题

标签: c# redirect asp.net-core asp.net-core-mvc .net-core


【解决方案1】:

为了使您的示例有效,您应该标记 [HttpGet("Index")] 您的 Index 方法

[Area("Dashboard")]
[Route("Dashboard/[controller]")]
public class HomeController : Controller
{
    // GET: Dashboard
    [HttpGet("Index")]
    public ActionResult Index()
    {
        return View();
    }

所以这里你的HomeController 以RESTFUL 方式工作,所以你可以使用public IActionResult Get()[HttpPost] public IActionResult Post()。如果这是你想要的,你可以用更通用的方式实现它

[Area("Dashboard")]
[Route("[area]/[controller]")]
public class HomeController : Controller
{
    // GET: Dashboard
    [HttpGet("Index")]
    public ActionResult Index()
    {
        return View();
    }

如果您不希望仪表板使用 RESTFUL,您应该删除 [HttpGet("Index")] 并将 [action] 添加到您的控制器属性中,所以如果会是这样的

[Area("Dashboard")]
[Route("[area]/[controller]/[action]")]
public class HomeController : Controller
{
    // GET: Dashboard
    public ActionResult Index()
    {
        return View();
    }

如果这符合您的目的,您可以完全省略 [Route("[area]/[controller]/[action]")],因为这是默认约定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2019-05-17
    • 2014-05-10
    • 1970-01-01
    • 2023-01-16
    • 2016-12-29
    • 2023-03-27
    相关资源
    最近更新 更多