首页 > 解决方案 > .NET Core RedirectToAction 导致 InvalidOperationException 错误

问题描述

我有一个页面位于:

  1. 一个叫做行动的区域
  2. 一个名为 Message 的控制器
  3. 一种称为索引的方法

当我登录到我的应用程序时,我会转到 HomeController,然后它会像这样重定向我:

public IActionResult Index()
{
    return RedirectToAction("Index", "Messages", new { area = "Action" });
}

但是,我收到此错误:

处理请求时发生未处理的异常。InvalidOperationException:没有路由与提供的值匹配。Microsoft.AspNetCore.Mvc.Infrastructure.RedirectToActionResultExecutor.ExecuteAsync(ActionContext 上下文,RedirectToActionResult 结果)

它很长,但我发现它与我在 Startup.cs 中的最后一个 await.next() 行有关:

app.Use(async (context, next) =>
{
    if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
    {
        string originalPath = context.Request.Path.Value;
        context.Items["originalPath"] = originalPath;
        context.Request.Path = "/Error/404";
        await next();
    }
    if (context.Response.StatusCode == 401 && !context.Response.HasStarted)
    {
        string originalPath = context.Request.Path.Value;
        context.Items["originalPath"] = originalPath;
        context.Request.Path = "/Error/401";
        await next();
    }

    if (context.Response.StatusCode == 302 && !context.Response.HasStarted && context.User.Identity.IsAuthenticated)
    {
        string originalPath = context.Request.Path.Value;
        context.Items["originalPath"] = originalPath;
        context.Request.Path = "/Error/302";
        await next();
    }
    if (context.Response.StatusCode == 400 && !context.Response.HasStarted)
    {
        string originalPath = context.Request.Path.Value;
        context.Items["originalPath"] = originalPath;
        context.Request.Path = "/Error/400";
        await next();
    }
    await next();
});

这也是我在 Startup.cs 中的路由:

app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "areas",
      template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    );
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

});

我在其他应用程序中有这个确切的 Startup.cs,它们运行得很好。不知道这个有什么问题?

编辑:

完整的例外:

cs + 等待下一个();Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics .DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

编辑2:

当我删除redirecttoaction并用return Page()替换它时;页面加载。这意味着区域重定向不起作用?

标签: c#asp.netasp.net-mvcasp.net-core

解决方案


return RedirectToAction("Index", "Messages", new { area = "Action" });

这将有一个类似 - Messages/Index/Action 这样的路由,所以请检查你想要什么以及它是否与参数一致。

如果您只需要 Mssage/ 或只需要 Index/ 为此创建新的路由配置。


推荐阅读