MVC跨Area地址写法

当Mvc使用Area进行区域划分后,如果需要访问根目录下的页面,需要指定一个空的Area作为参数:

@Url.Action("LoadSendingTask", new { area = "" })
An unhandled exception occurred while processing the request. InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered. Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) Stack Query Cookies Headers Routing InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered. Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) Microsoft.AspNetCore.Mvc.Razor.RazorPagePropertyActivator+<>c__DisplayClass8_0.<CreateActivateInfo>b__2(ViewContext context) Microsoft.Extensions.Internal.PropertyActivator<TContext>.Activate(object instance, TContext context) Microsoft.AspNetCore.Mvc.Razor.RazorPagePropertyActivator.Activate(object page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.RenderPartialViewAsync(TextWriter writer, object model, IView view) Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count) AspNetCoreGeneratedDocument.Views_Shared__Layout.<ExecuteAsync>b__28_1() Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync() AspNetCoreGeneratedDocument.Views_Shared__Layout.ExecuteAsync() Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderLayoutAsync(ViewContext context, ViewBufferTextWriter bodyWriter) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context) Show raw exception details 还是提示这个错误
最新发布
10-04
你仍然看到这个错误: ``` InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered. ``` 而且堆栈跟踪显示它发生在 **Razor 页面渲染期间**,特别是在 `_Layout.cshtml` 中加载某个部分视图时(可能是 `PartialTagHelper` 加载了 Identity 相关的 UI)。 --- ## 🔍 根本原因分析 虽然你在 `Program.cs` 中正确注册了: ```csharp AddDefaultIdentity<ApplicationUser>(...) ``` 但 ASP.NET Core 的 **默认 Identity UI 模板或布局文件中引用了 `UserManager<IdentityUser>`** —— 而这不是你注册的服务! > ❌ 容器里只有:`UserManager<ApplicationUser>` > ❌ 但它试图获取:`UserManager<IdentityUser>` → 找不到 → 抛出异常 --- ## ✅ 最常见的罪魁祸首:`_LoginPartial.cshtml` 这个文件通常位于: ``` /Views/Shared/_LoginPartial.cshtml ``` 或 ``` /Areas/Identity/Pages/_ViewStart.cshtml ``` 打开你的 `/Views/Shared/_LoginPartial.cshtml`,检查它的 `@inject` 行: ### ❌ 错误写法(导致问题): ```cshtml @inject SignInManager<IdentityUser> SignInManager @inject UserManager<IdentityUser> UserManager ``` ### ✅ 正确写法(必须改为): ```cshtml @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager ``` 📌 这是 **90% 以上此类问题的根源!** 即使你已经用 `ApplicationUser` 生成了 Identity 页面,但如果 `_LoginPartial.cshtml` 是旧版本、或者从模板复制来的,默认仍会使用 `IdentityUser`。 --- ## ✅ 解决方案步骤 ### ✅ 第一步:修改 `_LoginPartial.cshtml` 路径:`/Views/Shared/_LoginPartial.cshtml` 将这两行: ```cshtml @inject SignInManager<IdentityUser> SignInManager @inject UserManager<IdentityUser> UserManager ``` 替换为: ```cshtml @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager ``` ✅ 保存并刷新页面。 > 💡 提示:如果你没改过这个文件,可以去你项目的 `/Areas/Identity/Pages/Shared/` 看是否有替代版本。确保全局搜索 `SignInManager<IdentityUser>`。 --- ### ✅ 第二步:确认 `ApplicationUser` 和上下文一致 确保以下三点完全匹配: #### 1. `ApplicationDbContext` 继承自: ```csharp public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } ``` #### 2. `Program.cs` 中注册的是: ```csharp builder.Services.AddDefaultIdentity<ApplicationUser>(options => { ... }) .AddEntityFrameworkStores<ApplicationDbContext>(); ``` #### 3. 所有注入的地方都使用 `ApplicationUser`,包括: - 控制器 - Razor Pages (`*.cshtml.cs`) - Partial Views(如 `_LoginPartial.cshtml`) --- ### ✅ 第三步:清理与重建项目(重要!) 有时旧编译缓存会导致问题持续存在。 在项目根目录执行: ```bash dotnet clean dotnet build ``` 或者删除: - `bin/` 文件夹 - `obj/` 文件夹 然后重新运行。 --- ### ✅ 第四步:验证是否还有其他地方引用 `IdentityUser` 在 Visual Studio 或 VS Code 中全局搜索: ``` UserManager<IdentityUser> SignInManager<IdentityUser> IdentityUser ``` 特别注意这些位置: - `/Views/Shared/_LoginPartial.cshtml` - `/Pages/Shared/_LoginPartial.cshtml` - 自定义中间件或过滤器 - 任何 `.cshtml` 文件中的 `@inject` 全部替换为 `ApplicationUser`。 --- ### ✅ 第五步:测试访问 `/Identity/Account/Login` 不要直接访问主页(可能触发 `_LoginPartial` 提前报错),先单独测试: 👉 浏览器访问: ``` https://localhost:xxxx/Identity/Account/Login ``` 如果能正常打开登录页,并且没有异常,则说明 Identity 配置成功。 然后再访问 `/Home/Index` 或首页,看 `_LoginPartial` 是否正常显示“登录”或“你好, 用户”。 --- ## ✅ 示例:完整的 `_LoginPartial.cshtml` ```cshtml @using Microsoft.AspNetCore.Identity @using UserManagementSystem.Web.Models @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager <ul class="navbar-nav"> @if (SignInManager.IsSignedIn(User)) { <li class="nav-item"> <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage"> Hello @UserManager.GetUserName(User)! </a> </li> <li class="nav-item"> <form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })"> <button id="logout" type="submit" class="nav-link btn btn-link text-dark">Logout</button> </form> </li> } else { <li class="nav-item"> <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a> </li> } </ul> ``` --- ## ✅ 总结:你现在要做的事 | 操作 | 状态 | |------|------| | ✅ 修改 `_LoginPartial.cshtml` 中的 `@inject` 类型为 `ApplicationUser` | ⚠️ 极大概率就是这里的问题 | | ✅ 确认 `ApplicationDbContext : IdentityDbContext<ApplicationUser>` | ✅ 你应该已完成 | | ✅ `Program.cs` 使用 `AddDefaultIdentity<ApplicationUser>` | ✅ 已完成 | | ✅ 删除 `bin/obj` 并重新构建 | 推荐 | | ✅ 全局搜索 `IdentityUser` 并替换 | 必须做 | --- 做完以上操作后,**重启应用,再访问首页**,应该就不会再出现那个错误了。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值