我在使用HttpContext类时遇到了麻烦。 我可以访问HttpContext但不能调用它的函数。
我想在我写的助手类中使用HttpContext.Authentication。
我不能在我的帮助类中写下这样的内容(见下文):
var ageText = "32f"
var age = Double(ageText)
then do..
print(age!)
但是,我可以在我的控制器类中访问HttpContext。
我很感激任何帮助。提前谢谢。
答案 0 :(得分:3)
首先创建文件HttpContext.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace System.Web
{
public static class HttpContext
{
private static IHttpContextAccessor _contextAccessor;
public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;
internal static void Configure(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
}
public static class StaticHttpContextExtensions
{
public static void AddHttpContextAccessor(this IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
{
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
System.Web.HttpContext.Configure(httpContextAccessor);
return app;
}
}
}
启动文件中的下一步
public void ConfigureServices(IServiceCollection services)
...
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
...
最后,例如,在控制器之外,如果您需要当前用户名
var currentUsername = !string.IsNullOrEmpty(System.Web.HttpContext.Current?.User?.Identity?.Name)
? System.Web.HttpContext.Current.User.Identity.Name
: "Anonymous";
我测试了ASPNET Core 1.0和1.1
EDIT 对不起,我在你的启动文件中忘了配置添加这个:
public void Configure(IApplicationBuilder app)
...
app.UseStaticHttpContext();
...
答案 1 :(得分:3)
如果你想使用一个登录用户的帮助程序类,你应该改为使用扩展方法,它可以包裹IHttpContextAccessor
或HttpContext
本身。
public static class HttpContextExtensions
{
public static void SignInUser(this HttpContext context)
{
await context.Authentication.SignInAsync(..);
}
public static void SignInUser(this.IHttpContextAccessor contextAccessor)
{
// Calls the method from above
contextAccessor.HttpContext.SignInUser();
}
}
或者,如果您有更大的依赖关系链并需要其他注入服务,请将其转换为可注入类:
public class UserLogonService : IUserLogonService
{
private readonly IHttpContextAccessor contextAccessor;
public UserLogonService(IHttpContextAccessor contextAccessor)
{
if(contextAccessor==null)
throw new ArgumentNullException(nameof(contextAccessor));
this.contextAccessor = contextAccessor;
}
public void SingInUser()
{
contextAccessor.HttpContext.SignInUser();
}
}
并在Startup.Configure
方法中:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IUserLogonService, UserLogonService>();
现在,您可以通过构造函数在项目的任何位置注入IUserLogonService
,即
public class MyController
{
private readonly IUserLogonService userLogon;
public MyController(IUserLoggonService userLogon)
{
this.userLogon = userLogon;
}
public async Task<IActionResult> Login()
{
await userLogon.SignInUser();
}
}
它干净,分离,可以很容易地进行单元测试,而静态助手类无法做到这一点。