如何在服务器端 Blazor 中访问 HttpContext? [英] How do I access HttpContext in Server-side Blazor?

查看:60
本文介绍了如何在服务器端 Blazor 中访问 HttpContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问页面 (.cshtml) 中的 HttpContext,特别是请求和 cookie.尽管可用,HttpContextAccessor 总是在其 HttpContext 属性中存储一个 null 值.

I need to access HttpContext in a page (.cshtml) and in particular a request and then a cookie. Despite available, HttpContextAccessor always has a null value stored in its HttpContext property.

任何想法将不胜感激.

提前致谢.

我使用的 Blazor 版本是:0.7.0.

the Blazor version I use is: 0.7.0.

推荐答案

将以下内容添加到 Blazor.Web.App.Startup.cs:

Add the following to Blazor.Web.App.Startup.cs:

services.AddHttpContextAccessor();

你在.cshtml

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

注意:在撰写此答案时,访问 HttpContext 已按上述方式完成.从那时起,Blazor 一直在快速发展,并发生了根本性的变化.上面描述的用法绝对不推荐使用,但是,如果您从 .cshtml 页面访问 HttpContext,您仍然可以执行上述操作,这是合法且正确的.这并没有改变......因此,您可以访问 HttpContext 的唯一位置,甚至无需将 IHttpContextAccessor 添加到 DI 容器,就是 _Host.cshtml 文件,它是一个 Razor Pages 文件,扩展名为 .cshtml.当这个文件中的代码被执行时,Blazor 还没有诞生,这个文件的执行会服务于 Blazor Server App.请参阅此答案以了解如何正确执行...

Note: At the time when this answer was written, accessing the HttpContext was done as described above. Since then, Blazor has been under rapid development, and has fundamentally changed. It is definitely deprecated the usage described above, but alas, you can still do the above, which is legitimate and right, if you access the HttpContext from a .cshtml page. This has not changed... Thus the only place from which you can access the HttpContext, without even adding the IHttpContextAccessor to the DI container, is the _Host.cshtml file, which is a Razor Pages file, with the .cshtml extension. When the code in this file is executed, Blazor is still not born, and the execution of this file will be serving the Blazor Server App. Please, see this answer as to how to do it properly...

希望这有帮助...

这篇关于如何在服务器端 Blazor 中访问 HttpContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆