问题
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