【问题标题】:Disposable HtmlString Extension for Authorization purposes用于授权目的的一次性 HtmlString 扩展
【发布时间】:2013-03-10 17:00:56
【问题描述】:

我打算为 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" />
        --!>

但这会向客户透露一些我不想透露的信息,而且会使响应不必要地加重。

【问题讨论】:

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


    【解决方案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>
        }
    

    【讨论】:

    • 我明白了!谢谢!但是,如果我想 - 就像在 DIV 示例中一样 - 将逻辑委托给扩展方法怎么办?您会建议执行以下操作吗? @{using(var div = Html.BeginDiv()) { if(div.canBeDisplayed) { &lt;text&gt; This should appear inside a div &lt;input type="text" value="oi" /&gt; &lt;/text&gt; } } }
    • 视情况而定。如果您想根据不同的角色显示不同的内容,那么是的..我不明白为什么您不能将其委托给扩展..特别是如果您要做的不仅仅是:User.IsInRole("RoleName") .是您在实施时遇到困难,还是只想了解其他人对此的看法?
    • 我更想知道是否可以根据情况渲染不同的内容。但我认为不可能忽略text 标签中的内容并在我的一次性上下文中呈现一些不同的东西(不一定用于身份验证)。
    猜你喜欢
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2023-03-12
    • 2011-05-07
    相关资源
    最近更新 更多