中间件中的HttpContext .NET核心保存实例 [英] HttpContext .NET core saving instance in Middleware
本文介绍了中间件中的HttpContext .NET核心保存实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在中间件中存储HttpContext实例是否安全?
Is it safe to store an instance of HttpContext in a middleware?
示例:
public class TestMiddleware
{
private readonly RequestDelegate next;
private HttpContext context;
public TestMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
this.context = context;
我想在其他私有方法中使用它来处理它,因此我既可以将它作为参数传递给那些函数,也可以如示例中所示使用它.
I would like to use it in other private methods to work on it, so I can either pass it around as parameter to those function or use it as shown in the example.
但是线程安全吗?
推荐答案
但是线程安全吗?
But is it thread safe?
不,不是,因为中间件一定是单例.如果您将特定的HttpContext
存储在共享字段中,则它可能会在另一个请求期间被重用(这很糟糕).
No it's not, because middleware are necessarily singletons. If you store a specific HttpContext
in a shared field, it will be potentially reused during another request (which would be terrible).
这篇关于中间件中的HttpContext .NET核心保存实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文