HttpContext .NET core saving instance in Middleware

核能气质少年 提交于 2019-12-10 15:43:12

问题


Is it safe to store an instance of HttpContext in a middleware?

Example:

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?


回答1:


But is it thread safe?

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).



来源:https://stackoverflow.com/questions/38854690/httpcontext-net-core-saving-instance-in-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!