Created
August 3, 2019 13:53
-
-
Save gordonglas/2e9d6ceddbc63baaaec4e618181f8424 to your computer and use it in GitHub Desktop.
ASP.NET Core HttpContext.Current #aspnetcore
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
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace Common | |
{ | |
public static class Services | |
{ | |
public static bool IsWebSite { get; set; } | |
private static ServiceProvider serviceProvider; | |
public static void Init(bool isWebsite) | |
{ | |
IsWebSite = isWebsite; | |
if (IsWebSite) | |
{ | |
var services = new ServiceCollection(); | |
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); | |
services.AddTransient<IHttpContextWrapper, HttpContextWrapper>(); | |
serviceProvider = services.BuildServiceProvider(); | |
} | |
} | |
public static void Uninit() | |
{ | |
serviceProvider?.Dispose(); | |
} | |
public static T GetService<T>() | |
{ | |
if (!IsWebSite) | |
return default; | |
return serviceProvider.GetService<T>(); | |
} | |
public static HttpContext GetHttpContext(bool ignoreError = false) | |
{ | |
var httpContextWrapper = Services.GetService<IHttpContextWrapper>(); | |
var httpContext = httpContextWrapper?.HttpContext; | |
if (httpContext == null && !ignoreError) | |
throw new Exception("Failed to get HttpContext"); | |
return httpContext; | |
} | |
} | |
public interface IHttpContextWrapper | |
{ | |
HttpContext HttpContext { get; } | |
} | |
public class HttpContextWrapper : IHttpContextWrapper | |
{ | |
private readonly IHttpContextAccessor _httpContextAccessor; | |
public HttpContext HttpContext { get { return _httpContextAccessor.HttpContext; } } | |
public HttpContextWrapper(IHttpContextAccessor httpContextAccessor) | |
{ | |
_httpContextAccessor = httpContextAccessor; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment