【发布时间】:2022-01-05 22:23:22
【问题描述】:
我正在尝试在我的 Blazor WASM 项目中实现一个简单的 MVC 控制器,但我无法让路由正常工作。当我尝试访问它时,它总是将我重定向到 blazor“NotFound”组件。我花了很多时间尝试在我的 Startup.cs 中进行配置,但我的想法已经用完了。我正在.NET6 中的样板 WASM 项目上执行此操作。这就是我的 Startup.cs 的样子:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationServices();
services.ConfigurePersistenceServices(Configuration);
//services.AddMvc();
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseMiddleware<ExceptionMiddleware>();
app.UseCors(config =>
config
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
//.WithExposedHeaders("header1", "header")
);
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
endpoints.MapFallbackToFile("index.html");
});
}
这是我的 MVC 控制器:
[Route("[controller]/[action]")]
public class RoleManagerController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
public RoleManagerController(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
public async Task<IActionResult> Index()
{
var roles = await _roleManager.Roles.ToListAsync();
return View(roles);
}
[HttpPost]
public async Task<IActionResult> AddRole(string roleName)
{
if (roleName != null)
{
await _roleManager.CreateAsync(new IdentityRole(roleName.Trim()));
}
return RedirectToAction("Index");
}
}
【问题讨论】:
-
显然,当我完全写 /RoleManager/Index 时它可以工作,但如果我写 /rolemanager/index,它就不起作用。我怎样才能让它工作,所以路由忽略小写/大写?
-
我需要和你确认一下你的应用程序是否是Asp.net 6应用程序,因为众所周知,在.Net 6应用程序中它会使用program.cs文件来配置中间件和服务,而不是使用 Startup.cs 文件。或者,您创建一个 .Net 6 应用程序并同时使用 Program.cs 和 Startup.cs 文件。那么,能否分享一下program.cs文件中的相关代码?
-
二、在创建Blazor WASM项目时,是否勾选了Asp.net Core Hosted选项(勾选后会生成三个项目:Client、Server和Shared)?你想在客户端项目中添加控制器吗?通常,在 Blazor WASM 项目中(选中 Asp.net Core Hosted 选项),Client 项目包含提供 UI 的 Razor 组件,Server 项目包含 API 或 MVC 控制器,它们将处理和响应客户端请求。因此,控制器应该在 Blazor Server 应用程序中。
标签: asp.net-mvc asp.net-core blazor