我想在中间件中获取控制器名称。有很多答案使用如下的RequestContext
或RouteData
:
string controllerName = context.Request.RouteValues["controller"].ToString();
我尝试了这个方法,但它总是返回 null,有没有在 .NET 6 中实现的方法?
更新:.NET 版本为 6.0.100-rc.1.21458.32
我的 Program.cs:
var builder = WebApplication.CreateBuilder(args);
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "RMS.Admin.Api", Version = "v1" });
});
builder.Services.AddCoreServices(configuration);
var app = builder.Build();
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RMS.Admin.Api v1"));
}
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseElmah();
app.MapControllers();
app.UseAuditLogMiddleware();
app.UseErrorLoggingMiddleware();
app.Run();
中间件的调用方法:
public async Task Invoke(HttpContext httpContext, IUserContext userContext, IAuditLogContract auditLogContract)
{
System.Console.WriteLine(httpContext.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>());
auditLogContract.Add(new AuditLog
{
LoginStatus = (userContext.Id == "") ? false : true,
Controller = httpContext.Request.RouteValues["controller"]?.ToString(),
// More code here
});
await this.next(httpContext);
}
dotnet --version
也是个好主意。这样我们就可以使用相同的版本进行操作。 - Marco