【发布时间】:2021-05-12 20:59:17
【问题描述】:
我需要访问控制器内的 IApplicationBuilder。
我尝试过的:-
我已经编写了中间件(app.UseMyMiddleware)如下
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor httpContextAccessor)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMyMiddleware();
app.UseAuthentication();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
///TODO - Pass IApplicationBuilder to HttpContext
await _next(context);
}
}
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}
但我不知道如何在 Invoke 方法中将 IApplicationBuilder 传递给 HttpContext。所以,我可以在控制器中使用它。 我还提到了以下stackoverflow问答
- how to access IApplicationBuilder in a controller?
- .Net Core Middleware - Getting Form Data from Request
问题:-
-
Invoke 方法中如何将 IApplicationBuilder 传递给 HttpContext 以在控制器中使用它?
-
除了中间件,还有什么更好的方法可以访问控制器内部的 IApplicationBuilder 吗?
【问题讨论】:
-
IApplicationBuilder旨在在启动时构建应用程序,运行一次,而不是稍后在运行时运行。所以我认为它不能为您提供任何 runtime 服务或 api,您想要什么?这比如何提供更重要。 -
@KingKing 我想使用这个 IApplicationBuilder 在控制器中配置 Hangfire。您可以参考问题stackoverflow.com/questions/66022553/…了解更多详情
-
您以后无法在任何地方访问
IApplicationBuilder,但您可以在运行时使用UseWhen插入中间件。但是过滤条件不能利用你的MVC model binding,因为你只有HttpContext作为输入,你自己从原始源(查询字符串、路由数据、标题、表单、请求正文)中提取请求数据。您可以以某种方式实现一个设置,记住或发送每个请求的选定选项)。 -
@KingKing 你能给我举个例子我怎么能得到这个?
-
@KingKing 谢谢!为了您的努力,我会检查并通知您。