【问题标题】:How can I access the HTTPContext in a class derived from PageModel?如何访问派生自 PageModel 的类中的 HTTPContext?
【发布时间】:2021-10-10 17:40:20
【问题描述】:

为了简化 Razor 页面中会话变量的处理,我想在 PageModel 和 IndexModel 之间插入一个单独的类。

PageModel

现在我注意到在 MyPageModel 和 IndexModel 类中定义了 HTTPContext 但未设置(=null)。 但是,如果我直接从类 PageModel 派生类 IndexModel,一切都很好,我可以访问 HTTPContext 和会话变量。 到目前为止,启动中的设置都很好,因为其余页面都可以正常工作。 我究竟做错了什么?还是我忽略了什么?

类 MyPageModel 派生自 PageModel

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApp.Areas.Ansicht12.Pages
{
    public class MyPageModel : PageModel
    {
        string s1 = default;
        string s2 = default;
        int i3 = 0;

        public MyPageModel() : base()
        {
            s1 = HttpContext.Session.GetString("Var-1");
            s2 = HttpContext.Session.GetString("Var-2");
            i3 = (int)HttpContext.Session.GetInt32("Var-3");
        }

    }
}`

类 IndexModel 派生自 MyPageModel

namespace WebApp.Areas.Ansicht12.Pages
{
    public class IndexModel : MyPageModel
    {
        public IndexModel() : base()
        {
        }

        public void OnGet()
        {
        }
    }
}

【问题讨论】:

  • 我想你可以在上下文中传递......但是为什么这会使获取会话变量更容易?这些会话变量的用例是什么? (看来这些应该尽量避免……)
  • 嗨@Giuliano Casagrande,您的代码似乎与您所说的不符。我看不到您设置会话变量的任何地方,但您在MyPageModel 中阅读了会话。您是否需要在派生自MyPageModelIndexModel 中访问HttpContext?你在哪里设置会话变量?
  • @ pcalkins - 用例实际上非常简单。我想在视图中设置某些值并稍后检索它们。如果 IndexModel 直接从 PageModel 派生,这也很有效。带有上下文的提示对我来说似乎很有趣。如何传递派生类的上下文?在这一点上我还是有点弱。
  • @Rena - 会话变量设置在单独的位置。我不想用代码使我的帖子超载。这是设置会话变量的代码:using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.RazorPages; namespace WebApp.Areas.Ansicht12.Pages { public class Index1Model : PageModel { public void OnGet() { HttpContext.Session.SetString("Var-1", "Jupiter"); HttpContext.Session.SetString("Var-2", "Zeus"); HttpContext.Session.SetInt32("Var-3", 6554321); } } }
  • (抱歉,编辑器我还在纠结)

标签: c# asp.net-core razor-pages


【解决方案1】:

调用 Razor 页面的构造函数时,HttpContext 不可用。您可以使用IHttpContextAccessor 来满足您的要求。

我的页面模型:

public class MyPageModel : PageModel
{
    string s1 = default;
    string s2 = default;
    int i3 = 0;
    public MyPageModel(IHttpContextAccessor httpContextAccessor) :base()    
    {
        s1 = httpContextAccessor.HttpContext.Session.GetString("Var-1");
        s2 = httpContextAccessor.HttpContext.Session.GetString("Var-2");
        i3 = (int)httpContextAccessor.HttpContext.Session.GetInt32("Var-3");
    }            
}

索引模型:

public class IndexModel: MyPageModel
{
    public IndexModel(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
    {
    }

    public void OnGet()
    {
        
    }
}

一定要在Startup.ConfigureServices()方法中注册服务:

services.AddHttpContextAccessor();

【讨论】:

  • 就是这样!现在它起作用了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2016-05-01
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多