用于授权目的的一次性HtmlString扩展

时间:2013-01-21 12:04:09

标签: html asp.net-mvc razor extension-methods asp.net-authorization

我打算为MVC创建一个如下所示的扩展:

public static class DivExtension
{

    public static MvcHtmlElement BeginDiv(this HtmlHelper helper)
    {

        return new MvcDiv(helper.ViewContext).BeginDiv("","");
    } 
    public static MvcHtmlElement BeginDiv(this HtmlHelper helper, string id)
    {

        return new MvcDiv(helper.ViewContext).BeginDiv(id,"");
    } 
}

在Razor中,我可以这样使用它:

@{using(Html.BeginDiv())
  {
        <text>
              This should appear inside a div <input type="text" value="oi" />
        </text>
   }
}

这将生成以下HTML输出:

 <div>
   This should appear inside a div <input type="text" value="oi" />
 </div>

但是想象一下,我的代码不会只创建一个 div ,而是会收到一个表示角色的字符串,如果登录的用户不属于指定的角色,则此扩展名中的HTML应为抑制:

public static class HtmlAuthSuppressor
{

    public static MvcHtmlElement AuthHTML(this HtmlHelper helper, string roles)
    { 
        //some code that would allow suppression
    }  
}

如果我这样使用:

<b>Do you see something below?</b>
@{using(Html.AuthHTML("Role_Super_User"))
  {
        <text>
              Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" />
        </text>
   }
}

如果用户不属于指定的角色,最终的HTML输出将是:

<b>Do you see something below?</b>

这可能吗?

更新 我知道我可以生成这样的HTML:

   <b>Do you see something below?</b> 
     <!--   
              Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" />
        --!>

但这会向客户透露一些我不想透露的内容,除了让回应更加重要之外。

1 个答案:

答案 0 :(得分:1)

您无需为此构建扩展程序..只需执行此操作:

<b>Do you see something below?</b>

    @if (Request.IsAuthenticated && User.IsInRole("Role_Super_User"))
    {
        <text>
              Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" />
        </text>
    }