首页 > 解决方案 > 如何在 ASP NET Core 中处理 GET 请求

问题描述

我是 ASP.NET Core 的新手,我有一个任务,我需要创建一个自定义中间件,该中间件应该检查​​ HTTP 方法和查询字符串,以确定 GET 请求是否在查询字符串中设置了自定义键为 true .

对于带有预期查询字符串的 GET 请求,中间件函数将“Hello from Custom Middleware”字符串添加到响应正文中。然后中间件组件将请求传递给请求管道中的下一个组件。我需要使用 lambda 表达式来执行此操作,而无需创建控制器、类等。

查询字符串看起来像?custom=true.

现在我做了以下。请向我解释我出错的地方以及我们如何处理/使用 GET 请求?

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Use(async (context, next) =>
    {

       var customQuery = context.Request.Query["custom"];
        if (customQuery == true)
        {
            await context.Response.WriteAsync("Hello from Custom Middleware");
            return;
        }

        await next();
    });

    app.UseRouting();

标签: c#asp.net-core

解决方案


我意识到这是一个愚蠢的问题),但也许有人需要我的回答

     app.Use(async (context, next) =>
        {  
            var strcustomValue = context.Request.Query["custom"];
            if (!string.IsNullOrEmpty(strcustomValue))
            {
                bool customValue = bool.Parse(strcustomValue);

                if (customValue == true)
                {
                    await context.Response.WriteAsync("Hello from Custom Middleware");
                }
                else
                {
                    await next();
                }
            }
        });

推荐阅读