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

查看:842
本文介绍了如何在服务器端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.

任何想法都将不胜感激.

Any ideas would be much appreciated.

谢谢.

我使用的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();

您还需要在<component-name>.cshtml

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

注意:在编写此答案时,如上所述已完成对HttpContext的访问.从那时起,Blazor一直在飞速发展,并且发生了根本性的变化.绝对不建议使用上述用法,但是,如果您从.cshtml页面访问HttpContext,则仍然可以执行上述操作,这是正确且正确的.这并没有改变...因此,即使没有将IHttpContextAccessor添加到DI容器,也可以访问HttpContext的唯一位置是_Host.cshtml文件,该文件是Razor Pages文件,扩展名为.cshtml.当执行该文件中的代码时,Blazor仍然没有出生,并且该文件的执行将服务于Blazor Server应用程序.请参阅此答案有关如何正确执行此操作...

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...

希望这对您有帮助...

Hope this helps...

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

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