Telerik UI for ASP.NET Core是用于跨平台响应式Web和云开发的最完整的UI工具集,拥有超过60个由Kendo UI支持的ASP.NET核心组件。它的响应式和自适应的HTML5 格,提供从过滤、排序数据到分页和分层数据分组等100多项高级功能。
什么是HttpContext/strong>
它保存有关Http请求的当前信息,包含诸如授权、身份验证、请求、响应、会话、项目、用户、formOptions等信息。每个HTTP请求都会使用当前信息创建HttpContext的新对象。
如何在控制器中访问HttpContext/strong>
控制器公开了ControllerBase.HttpContext属性,因此我们可以直接访问当前Http请求的HttpContext属性,最佳的方法是始终使用默认的HttpContextAccessor通过DI访问HttpContext。
要在服务中使用HttpContext,我们需要执行以下两个步骤:
Step 1:使用.NET Core内置依赖项注入容器注册依赖项,如下所示,在ConfigureServices方法的Startup.cs类中:
public void ConfigureServices(IServiceCollection services){services.AddControllers();//IHttpContextAccessor registerservices.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中已弃用。

标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!