How to access session from a view in ASP .NET Core MVC 1.0

六月ゝ 毕业季﹏ 提交于 2019-12-05 03:48:24

The following should work in the view: Context.Session.TryGetValue

If you are using the SessionExtensions then Context.Session.GetString will work.

Injecting IHttpContextAccessor does work, but starting with ASP.NET Core 1.0.0 RC2, the IHttpContextAcessor is not registered by default, because it has significant performance overhead per request. See this GitHub announcement for more information.

Tratcher posted:

IHttpContextAccessor can be used to access the HttpContext for the current thread. However, maintaining this state has non-trivial performance costs so it has been removed from the default set of services.

Developers that depend on it can add it back as needed: services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

But in your use case, I would suggest using a ViewComponent, which is a reusable piece of View with logic, that do not depend on a controller.

The documentation can be found here.

In your Views you would simply embed it with

@await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })

or

@Component.Invoke("PriorityList", new { maxPriority = 2, isDone = false })

for synchronous calls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!