AABBbaby

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

如何在ASP.NET Core中获取HttpContext?

Telerik UI for ASP.NET Core最新版下载

Telerik UI for ASP.NET Core是用于跨平台响应式Web和云开发的最完整的UI工具集,拥有超过60个由Kendo UI支持的ASP.NET核心组件。它的响应式和自适应的HTML5网格,提供从过滤、排序数据到分页和分层数据分组等100多项高级功能。

什么是HttpContext?

它保存有关Http请求的当前信息,包含诸如授权、身份验证、请求、响应、会话、项目、用户、formOptions等信息。每个HTTP请求都会使用当前信息创建HttpContext的新对象。

如何在控制器中访问HttpContext?

控制器公开了ControllerBase.HttpContext属性,因此我们可以直接访问当前Http请求的HttpContext属性,最佳的方法是始终使用默认的HttpContextAccessor通过DI访问HttpContext。

要在服务中使用HttpContext,我们需要执行以下两个步骤:

Step 1:使用.NET Core内置依赖项注入容器注册依赖项,如下所示,在ConfigureServices方法的Startup.cs类中:

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//IHttpContextAccessor register
services.AddHttpContextAccessor();
services.AddTransient<IUserService, UserService>();
}

Step 2:接下来,将IHttpContextAccessor注入到创建的服务构造函数中,并如下所示访问HttpContext的属性:

namespace Get_HttpContext_ASP.NET_Core
{
using Microsoft.AspNetCore.Http;

public class UserService : IUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;

public UserService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public string GetLoginUserName()
{
return _httpContextAccessor.HttpContext.User.Identity.Name;
}
}
}

现在,您可以访问服务中HttpContext的所有属性,如以上两个步骤所示。

注意:在.NET中,它被称为HttpContext.Current,但是在ASP.NET Core中已弃用。


了解最新Kendo UI最新资讯,请关注Telerik中文网!

posted on   AABBbaby  阅读(387)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示