在ASP.NET Core5.0中访问HttpContext的方法步骤
ASP.NET Core 应用通过 IHttpContextAessor 接口及其默认实现 HttpContextAessor 访问 HttpContext。 只有在需要访问服务内的 HttpContext 时,才有必要使用 IHttpContextAessor。
通过 Razor Pages 使用 HttpContext
Razor Pages PageModel 公开 HttpContext 属性:
public class AboutModel : PageModel { public string Message { get; set; } public void OnGet() { Message = HttpContext.Request.PathBase; } }
通过 Razor 视图使用 HttpContext
Razor 视图通过视图上的 RazorPage.Context 属性直接公开 HttpContext。 狼蚁网站SEO优化的示例使用 Windows 身份验证检索 Intra 应用中的当前用户名:
@{ var username = Context.User.Identity.Name; ... }
通过控制器使用 HttpContext
控制器公开 ControllerBase.HttpContext 属性:
public class HomeController : Controller { public IActionResult About() { var pathBase = HttpContext.Request.PathBase; ... return View(); } }
通过中间件使用 HttpContext
使用自定义中间件组件时,HttpContext 传递到 Invoke 或 InvokeAsync 方法,在中间件配置后可供访问:
public class MyCustomMiddleware { public Task InvokeAsync(HttpContext context) { ... } }
通过自定义组件使用 HttpContext
对于需要访问 HttpContext 的其他框架和自定义组件,建议使用内置的依赖项注入容器来注册依赖项。 依赖项注入容器向任意类提供 IHttpContextAessor,以供类在自己的构造函数中将它声明为依赖项:
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddHttpContextAessor(); services.AddTransient<IUserRepository, UserRepository>(); }
如下示例中:
- UserRepository 声明自己对 IHttpContextAessor 的依赖。
- 当依赖项注入容器解析依赖链并创建 UserRepository 实例时,就会注入依赖 项。
public class UserRepository : IUserRepository { private readonly IHttpContextAessor _httpContextAessor; public UserRepository(IHttpContextAessor httpContextAessor) { _httpContextAessor = httpContextAessor; } public void LogCurrentUser() { var username = _httpContextAessor.HttpContext.User.Identity.Name; service.LogAessRequest(username); } }
从后台线程访问 HttpContext
HttpContext 不是线程安全型。 在处理请求之外读取或写入 HttpContext 的属性可能会导致 NullReferenceException。
要使用 HttpContext 数据安全地执行后台工作,请执行以下操作:
- 在请求处理过程中复制所需的数据。
- 将复制的数据传递给后台任务。
要避免不安全代码,请勿将 HttpContext 传递给执行后台工作的方法。 而是传递所需要的数据。 在以下示例中,调用 SendEmailCore,开始发送电子邮件。 将 correlationId 传递到 SendEmailCore,而不是 HttpContext。 代码执行不会等待 SendEmailCore 完成:
public class EmailController : Controller { public IActionResult SendEmail(string email) { var correlationId = HttpContext.Request.Headers["x-correlation-id"].ToString(); _ = SendEmailCore(correlationId); return View(); } private async Task SendEmailCore(string correlationId) { ... } }
到此这篇关于在ASP.NET Core5.0中访问HttpContext的方法步骤的文章就介绍到这了,更多相关ASP.NET Core 访问 HttpContext内容请搜索狼蚁SEO以前的文章或继续浏览狼蚁网站SEO优化的相关文章希望大家以后多多支持狼蚁SEO!
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程