WorkContext.CurrentUser .~不可用

时间:2017-06-11 13:08:29

标签: c# asp.net asp.net-mvc orchardcms

我有以下代码:

<input type="text" name="username" value="@WorkContext.CurrentUser.UserName"/>

但是,在我看来,当我尝试查看该页面时,我收到以下错误:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the 
current web request. Please review the stack trace for more information about 
the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to 
an instance of an object.

Source Error: 


Line 102:                <label for="textinput" class="control-label col-sm3">Notes</label>
Line 103:                <div class="col-sm-9">
Line 104:                    <textarea class="form-control" id="Notes">@port.Notes</textarea>
Line 105:                </div>
Line 106:            </div>

我已尝试以下方法来修复它:

    <input type="text"name="username"value="@(WorkContext.CurrentUser.UserName)"/>

还尝试在我的视图顶部添加以下内容:

@using Orchard
@{
   WorkContext wContext = new WorkContext();
}

然后将我的初始代码更改为:

<input type="text" name="username" value="@wContext.CurrentUser.UserName"/>

然而,这给了我错误:

Cannot create an instance of the abstract class or interface 'WorkContext'

有人可以提供任何建议吗?

编辑:这不是port.Notes变量的问题,如果我删除有关workcontext的代码,页面渲染正常,我完全删除了有关端口变量的代码然后它抛出相同的错误但指向关闭curyl brace。为了证明这不是问题,我创建了一个新的ActionResult和视图,并且只包含@using Orchard和@WorkContext.CurrentUser.UserName并且它仍然失败:异常详细信息:System.NullReferenceException:对象引用未设置为an的实例对象

  • Odatia

1 个答案:

答案 0 :(得分:1)

正如Chetan已经回答的那样,你得到了原始异常,因为WorkContext.CurrentUsernull。原因很简单:没有当前用户,即没有经过身份验证的用户(您在没有登录的情况下浏览网站)。

这是正常的,你应该添加一个空检查作为防范NRE的最基本措施。

在旁注中,请确保选中您创建的输入字段以包含服务器端的实际当前用户。否则,每个登录的用户都可以编辑页面的HTML并更改值,允许它们例如以另一个用户的名字发帖。