如何通过 Web API 控制器转发所有 SPA 页面请求?



我有一个angular application,我希望所有首先通过它的请求都通过API Controller,以便检查角色或授权。我不想更改我的所有urls以使它们与Controller匹配:

我希望该服务器上的所有请求首先通过控制器:

路由示例

localhost:4200/index
localhost:4200/details
localhost:4200/data/3

目前我在Startup中的管道如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa => {
spa.Options.SourcePath = "WorkingApp";
if (env.IsDevelopment()) {
spa.UseAngularCliServer(npmScript: "start");
}
});
}

控制器

using Serilog;
public class AuthController : ControllerBase {
[HttpGet("[action]")]
public async Task<ActionResult<AuthenticationResult>> GetUsernameAndRolesAsync() {
try {
var result = new AuthenticationResult() {
Username = User.Identity.Name,
Roles = User.Claims.Where(x => x.Type == ClaimTypes.Role)
.Select(x => x.Value)
.ToList()
};
Log.Information($"GetUsernameAndRolesAsync returned IsAuthenticated={User.Identity.IsAuthenticated} for username {result.Username}");
foreach (var role in result.Roles) {
Log.Information($"GetUsernameAndRolesAsync returned role: {role} for username: {result.Username}");
}
return result;
} catch (Exception ex) {
return new StatusCodeResult(500);
}
}
}

public class AuthenticationResult {
public string Username { get; set; }
public List<string> Roles { get; set; }
}

如何更改MVC模板和管道,以便所有请求无缝通过控制器?

对于此要求

我希望首先通过它的所有请求都通过 API 控制器,以便检查角色或授权

这不是推荐的方法,因为如果要检查用户访问资源角度的权限,则已经提供了guard。保护用于检查用户权限和授权。

.Net Core Web API 具有Authorize属性来检查用户访问 API 资源的权限,通常使用实现 JWT 所需的 SPA。令牌将存储在客户端,当用户请求API资源时,我们会在标头中发送带有令牌的请求,以使服务器知道谁在请求资源

最新更新