This repository has been archived by the owner on Nov 20, 2018. It is now read-only.
Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
HttpAbstractions/src/Microsoft.AspNetCore.Http/HttpContextAccessor.cs
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
41 lines (36 sloc)
1.3 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) .NET Foundation. All rights reserved. | |
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | |
using System.Threading; | |
namespace Microsoft.AspNetCore.Http | |
{ | |
public class HttpContextAccessor : IHttpContextAccessor | |
{ | |
private static AsyncLocal<HttpContextHolder> _httpContextCurrent = new AsyncLocal<HttpContextHolder>(); | |
public HttpContext HttpContext | |
{ | |
get | |
{ | |
return _httpContextCurrent.Value?.Context; | |
} | |
set | |
{ | |
var holder = _httpContextCurrent.Value; | |
if (holder != null) | |
{ | |
// Clear current HttpContext trapped in the AsyncLocals, as its done. | |
holder.Context = null; | |
} | |
if (value != null) | |
{ | |
// Use an object indirection to hold the HttpContext in the AsyncLocal, | |
// so it can be cleared in all ExecutionContexts when its cleared. | |
_httpContextCurrent.Value = new HttpContextHolder { Context = value }; | |
} | |
} | |
} | |
private class HttpContextHolder | |
{ | |
public HttpContext Context; | |
} | |
} | |
} |