字段初始值设定项无法引用非静态字段,方法或属性'Controller.HttpContext' [英] A field initializer cannot reference the non-static field, method, or property 'Controller.HttpContext'

查看:118
本文介绍了字段初始值设定项无法引用非静态字段,方法或属性'Controller.HttpContext'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过执行以下操作来获取正在控制器中使用该应用程序的用户:

I am trying to get the user that is using the application in the controller by doing this:

public class TableNameController : Controller
{
    private ConnectionString db = new ConnectionString();
    private string userIdentity = HttpContext.User.Identity.Name.Split('\\')[1].Replace(".", " ");

当我这样做时,我在HttpContext下弯弯曲曲地说:

When I do this, I get a red squiggly under HttpContext saying:

字段初始化器无法引用非静态字段,方法或属性'Controller.HttpContext'

A field initializer cannot reference the non-static field, method, or property 'Controller.HttpContext'

在静态上下文中无法访问非静态属性'HttpContext'

Cannot access non-static property 'HttpContext' in static context

我该如何解决?

推荐答案

您不能将字段初始化程序用于尝试执行的操作,但可以轻松地为此使用实例构造函数:

You cannot use field initializer for what you trying to do, but you can easily use instance constructor for that:

public class TableNameController : Controller
{
    ...
    private string userIdentity;

    public TableNameController() {
        userIdentity = HttpContext.User.Identity.Name.Split('\\')[1].Replace(".", " ");
    }

    ...

这篇关于字段初始值设定项无法引用非静态字段,方法或属性'Controller.HttpContext'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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