与自定义属性MVC角色 [英] MVC roles with custom properties

查看:117
本文介绍了与自定义属性MVC角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找到如何在MVC 4(.NET 4.5)实现授权,并已被明确地念叨<一href="http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx"相对=nofollow> SimpleMembership 。是否有任何MVC典型或接受的方式有具有附加属性除了一个名字的角色?

例如,假设你在设计一个CMS,并希望能有一个角色叫像作家让用户进行修改。不过,你也想的作用是限制单个页面。我知道这样做的唯一方法是对每一个页面,其中每个角色可能被命名为类似于 Writer_℃的独立作用; PAGEID&GT; 。是否有任何模式,它比这更好的,或者是pretty的多,我们所能做?

在理想情况下,我想知道是否有会是一些方法,以便能够有一些远程这样的:

 公众的ActionResult EditPage(页){
    WriterRole角色=新WriterRole(页);

    如果(!User.IsInRole(角色)){
        返回NotAuthorized();
    }

    // 编辑...
}
 

相反的:

 公众的ActionResult EditPage(页){
    字符串的作用=Writer_+ page.Id;

    如果(!User.IsInRole(角色)){
        返回NotAuthorized();
    }

    // 编辑...
}
 

解决方案

我会做的是有一个作家的角色,然后检查用户ID,看的人拥有可编辑的资源。

  [授权(角色=作家)
公众的ActionResult EditPage(页){
    如果(User.UserId == page.UserId){...}
}
 

I'm looking into how to implement authorization in MVC 4 (.NET 4.5), and have specifically been reading about SimpleMembership. Is there any typical or accepted way in MVC to have roles that have additional properties aside from a name?

For example, suppose you were designing a CMS, and wanted to be able to have a role called something like Writer that let a user make modifications. However, you also want the role to be restrictive to a single page. The only way that I know of to do that would be to have a separate role for each page, where each role might be named something like Writer_<PageID>. Is there any pattern that's nicer than this, or is that pretty much all we can do?

Ideally, I'm wondering if there'd be some way to be able to have something remotely like:

public ActionResult EditPage(Page page) {
    WriterRole role = new WriterRole(page);

    if (!User.IsInRole(role)) {
        return NotAuthorized();
    }

    // Edit...
}

Instead of:

public ActionResult EditPage(Page page) {
    string role = "Writer_" + page.Id;

    if (!User.IsInRole(role)) {
        return NotAuthorized();
    }

    // Edit...
}

解决方案

What I would do is have one Writer role then check the UserId to see if the person owns the editable resource.

[Authorize(Roles = "Writer")]
public ActionResult EditPage(Page page) {
    if (User.UserId == page.UserId) { ... }
}

这篇关于与自定义属性MVC角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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