Asp.net mvc 如何在mvc HtmlExtension方法中访问用户身份详细信息?

Asp.net mvc 如何在mvc HtmlExtension方法中访问用户身份详细信息?,asp.net-mvc,asp.net-identity,Asp.net Mvc,Asp.net Identity,大家好,谢谢你们提前回复 我必须在许多页面中显示许多操作链接,并且我在用户角色之间拥有授权,所以我正在视图中编写if-else,但我想让它简短一些,这就是为什么我选择htmlHelper扩展方法的原因这是我的代码 public static MvcHtmlString ValidationActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, stri

大家好,谢谢你们提前回复

我必须在许多页面中显示许多操作链接,并且我在用户角色之间拥有授权,所以我正在视图中编写if-else,但我想让它简短一些,这就是为什么我选择htmlHelper扩展方法的原因这是我的代码

   public static MvcHtmlString ValidationActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string AllowedRole)
{
     if (User.IsInRole(AllowedRole))// its given me error The User dosent exist in current context Am i missing some namespace or what ?
     {
                htmlHelper.ActionLink(linkText, actionName);
     }                      
}

您可以使用访问扩展方法中的
User

public static MvcHtmlString ValidationActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string AllowedRole)
{
    var user = htmlHelper.ViewContext.HttpContext.User;

或者,您可以通过向扩展方法添加一个附加参数将
User
传递给该方法。

谢谢@StephenMuecke您的两个选项都起作用了,非常感谢。我如何标记您的答案以更正我的声誉低于15您只需单击答案左侧的勾号我已经做了很多次,但出现了一条消息“谢谢你的反馈!一旦您赢得总共15个声誉,您的投票将更改公开显示的帖子分数“,,只想投票支持您的答案。您还不能投票(通过单击箭头),但可以通过单击勾号接受-