简体   繁体   English

.Net核心中间件-从请求中获取表单数据

[英].Net Core Middleware - Getting Form Data from Request

In a .NET Core Web Application I am using middleware (app.UseMyMiddleware) to add some logging on each request: 在.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);
            }
        }

This all works fine and I can grab most of what I need from the request but what I need next is the Form Data on a POST method. 一切正常,我可以从请求中获取大部分需求,但接下来需要的是POST方法上的Form Data。

context.Request.Form is an available option but when debugging I hover over it and see "The function evaluation requires all thread to run". context.Request.Form是一个可用的选项,但是在调试时,我将鼠标悬停在它上面,请参阅“函数评估要求所有线程都运行”。 If I try to use it the application just hangs. 如果我尝试使用它,应用程序将挂起。

What do I need to do to access Request.Form or is there an alternative property with POST data that I'm not seeing? 我需要做什么才能访问Request.Form,或者我没有看到带有POST数据的替代属性?

You can create a separate middleware rather than an inline one and then call the HitDetails.StoreHitDetails from there. 您可以创建单独的中间件而不是嵌入式中间件,然后从那里调用HitDetails.StoreHitDetails

public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        HitDetails.StoreHitDetails(context);

        await _next(context);
    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyMiddleware>();
    }
}

That way you can continue using app.UseMyMiddleware(); 这样,您可以继续使用app.UseMyMiddleware(); and you don't have to run it using Task.Run as you mentioned. 而且您不必如上所述使用Task.Run来运行它。

Or you can just try calling HitDetails.StoreHitDetails(context) without wrapping it in Task.Run 或者,您可以尝试调用HitDetails.StoreHitDetails(context)而不将其包装在Task.Run

Edited 编辑

Check if your Request has a correct content type: 检查您的Request是否具有正确的内容类型:

if (context.Request.HasFormContentType)
{
    IFormCollection form;
    form = context.Request.Form; // sync
    // Or
    form = await context.Request.ReadFormAsync(); // async

    string param1 = form["param1"];
    string param2 = form["param2"];
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以在 .net core 中重定向来自中间件的请求 - Is it possible to redirect request from middleware in .net core 从 ASP.NET Core 2.0 中的中间件获取 HttpContext 中的请求正文 - getting the request body inside HttpContext from a Middleware in asp.net core 2.0 从表单asp.net核心获取数据 - Getting data from form asp.net core 带cookie中间件的asp.net核心-授权访问请求数据 - asp.net core w/ cookie middleware - accessing request data on authorization 从 ASP.NET Core HttpContext.Request 的 multipart/form-data 内容读取 excel 文件? - Reading excel file from ASP.NET Core HttpContext.Request of multipart/form-data content? 如何从ASP.NET Core 2.0中的自定义中间件请求身份验证 - How to request authentication from custom middleware in ASP.NET Core 2.0 从中间件中排除路由 - .net core - Exclude route from middleware - .net core 在 .Net Core 3.0 中间件中使用自定义标头填充 HTTP 请求标头 - Populate HTTP request headers with custom header in .Net Core 3.0 middleware 中间件异常后获取请求正文。 .NET 核心 3.1 - Get request body after exception in middleware. .NET Core 3.1 .net 核心 webapi 中间件中是否有处理取消请求的方法 - Is there a mean to handle cancel request in .net core webapi middleware
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM