首页 > 解决方案 > 如何“覆盖”AccountController 的 Index()?

问题描述

您可能已经知道,AccountController 自 2.0 起不再可用。多亏了 New Scaffolded Item,一切都可以通过 Identity.Pages 进行管理。

但我的问题是,如何从 url 中检索参数?

在 2.0 中,我们会这样做:

[Authorize]
public class AccountController : Controller
{
    [HttpGet]
    public ActionResult Index(string parameter)
    { 
        [...]
    }
}

但是在 3.1 中我们怎么做呢,因为 AccountController 已经不存在了?

标签: c#asp.net-coreasp.net-core-identity

解决方案


我假设您同时使用 AccountController 和 Scaffold Identity,并希望导航到 AccountController 中的操作方法并传输参数。

如果是这种情况,您可以参考以下示例代码:

  1. 在url末尾添加参数:

    查看页面中的代码:

      <a href="~/Account/Login?name='aaa'" >Login</a>
    

    登录操作方法中的代码:

     public class AccountController : Controller
     {
         public IActionResult Index()
         {
             return View();
         }
         [HttpGet] 
         public IActionResult Login(string name)
         {
             ViewData["name"] = name;
             return View();
         }
     }
    
  2. 使用路由属性

    查看页面中的代码:

    <a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Login" asp-route-name="dillion">Account</a>
    

    或者

     <a href="~/Account/Login/aaa >Login</a>
    

    登录操作方法中的代码:

     public class AccountController : Controller
     {
         public IActionResult Index()
         {
             return View();
         }
         [HttpGet]
         [Route("Account/Login/{name}")]
         public IActionResult Login(string name)
         {
             ViewData["name"] = name;
             return View();
         }
     }
    

截图如下: 在此处输入图像描述

对于 Scaffold Identity 页面,如果您检查 url,您可以看到它们在 Identity 区域中,链接如下:

  <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>

参考:

在 ASP.NET Core 中路由到控制器操作

ASP.NET Core 中的锚标记助手


推荐阅读