在 .NET Core Web 应用程序中,我使用中间件 (app.UseMyMiddleware) 在每个请求上添加一些日志记录:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(MyMiddleware.GenericExceptionHandler);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMyMiddleware();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public static void UseMyMiddleware(this IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
await Task.Run(() => HitDetails.StoreHitDetails(context));
await next.Invoke();
});
}
public static void StoreHitDetails(HttpContext context)
{
var config = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));
var settings = new Settings(config);
var connectionString = config.GetConnectionString("Common");
var features = context.Features.Get<IHttpRequestFeature>();
var url = $"{features.Scheme}://{context.Request.Host.Value}{features.RawTarget}";
var parameters = new
{
SYSTEM_CODE = settings.SystemName,
REMOTE_HOST = context.Connection.RemoteIpAddress.ToString(),
HTTP_REFERER = context.Request.Headers["Referer"].ToString(),
HTTP_URL = url,
LOCAL_ADDR = context.Connection.LocalIpAddress.ToString(),
AUTH_USER = context.User.Identity.Name
};
using (IDbConnection db = new SqlConnection(connectionString))
{
db.Query("StoreHitDetails", parameters, commandType: CommandType.StoredProcedure);
}
}
这一切都工作正常,我可以从请求中获取我需要的大部分内容,但接下来我需要的是 POST 方法上的表单数据。
context.Request.Form 是一个可用选项,但在调试时我将鼠标悬停在它上面并看到“函数评估需要所有线程运行”。如果我尝试使用它,应用程序就会挂起。
我需要做什么才能访问 Request.Form 或者是否有我没有看到的带有 POST 数据的替代属性?