当前位置:首页 > Web开发 > 正文

就会注入依赖项

2024-07-17 Web开发

使用HttpContext的具体场景:

1. 在Controller层访谒HttpContext

2. 在中间件中使用HttpContext

3. 在数据访谒层使用HttpContext

4. 在后台线程中访谒HttpContext

5. 在Razor页面模型中访谒HttpContext

6. 在Razor视图中访谒HttpContext

解决方案

1.在Controller层访谒HttpContext

示例代码中HomeController担任与Controller抽象类

Controller父类中担任与ControllerBase抽象类

此中ControllerBase抽象类有供给了对HttpContext的访谒

技术图片

所以,我们在Controller这一层可以按以下方法访谒HttpContext:

public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private string customer; public HomeController(ILogger<HomeController> logger) { _logger = logger; customer = HttpContext.Request.Form["CustomerId"]; } }

 二:在中间件中使用HttpContext

自界说扩展中间件中,实现Invoke要领,手机qq空间相册破解器 ,HttpContext通过参数的方法通报到中间件的业务逻辑中。

public async Task Invoke(HttpContext context)

 

public class CustomerMiddleware { private readonly RequestDelegate _next; public CustomerMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { // Do something with context near the beginning of request processing. await _next.Invoke(context); // Clean up. } }

三、 在数据访谒层使用HttpContext

声明一个User的仓储类,实现对User的长期化。如下代码中,

UserRepository依赖 IHttpContextAccessor

通过ASP.NET Core依赖注入容器解析依赖链并创建 UserRepository 实例时,就会注入依赖项。

public class UserRepository: IUserRepository { private readonly IHttpContextAccessor _httpContextAccessor; public UserRepository(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public void AddUser(User user) { var username = _httpContextAccessor.HttpContext.User.Identity.Name; //Save User to DB } }

使用ASP.NET Core内置的依赖项注入容器来注册依赖项。 依赖项注入容器向任意类供给 IHttpContextAccessor,以供类在本身的结构函数中将它声明为依赖项:

public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddHttpContextAccessor(); services.AddTransient<IUserRepository, UserRepository>(); }

四:在后台线程中访谒HttpContext

HttpContext 不是线程安适的。 在措置惩罚惩罚请求之外读取或写入 HttpContext 的属性,可能会导致 NullReferenceException空引用异常。

如何再后台线程中使用HttpContext呢?保举的做法:

1. 在请求措置惩罚惩罚过程中复制所需的数据。

2. 将复制的数据通报给后台任务。

技术图片

五:在Razor页面模型中访谒HttpContext

Razor页面模型的父类PageModel供给了HttpContext的访谒,如下代码:

六、在Razor视图中访谒HttpContext

Razor 视图通过视图上的 RazorPage.Context 属性直接果然 HttpContext

@{ ViewData["Title"] = "Home Page"; var username = Context.User.Identity.Name; }

HttpContext访谒的正确姿势

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/27363.html