c# - 如何在 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();
解决方案
我意识到这是一个愚蠢的问题),但也许有人需要我的回答
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();
}
}
});
推荐阅读
- firebase - Firebase 中的事件转化
- python - 数据流:使用 python 管道更新 BigQuery 行
- python - 放置海龟设置的安全地方?
- angular - 无法读取未定义的属性“setParent”
- java - 上滑面板(Java 到 Kotlin)
- ejb - IllegalArgumentException:找不到密钥“javax.security.auth.Subject.container”的处理程序
- datatables - 使用 table.row() 插入行后数据表的第二个分页和搜索栏
- mysql - 使用带有插入的参数的JMeter sql语法错误
- java - 不断收到“错误:在
无法找到属性 android:font" android leanback - python - 将 Python 脚本转换为 exe 并包含 selenium 浏览器