小编cha*_*ura的帖子

ASP.NET MVC 4使用权限代码自定义授权属性(无角色)

我需要在我的MVC 4应用程序中根据用户权限级别(没有角色,只分配给用户的CRUD操作级别的权限级别)来控制对视图的访问.

示例如下AuthorizeUser将是我的自定义属性abd我需要像下面一样使用它.

[AuthorizeUser(AccessLevels="Read Invoice, Update Invoice")]
public ActionResult UpdateInvoice(int invoiceId)
{
   // some code...
   return View();
}


[AuthorizeUser(AccessLevels="Create Invoice")]
public ActionResult CreateNewInvoice()
{
  // some code...
  return View();
}


[AuthorizeUser(AccessLevels="Delete Invoice")]
public ActionResult DeleteInvoice(int invoiceId)
{
  // some code...
  return View();
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?怎么样?提前致谢...

Chatura

authorization custom-attributes asp.net-mvc-4

117
推荐指数
3
解决办法
14万
查看次数

ASP.NET MVC 4自定义Authorize属性 - 如何将未经授权的用户重定向到错误页面?

我正在使用自定义授权属性根据用户的权限级别授权用户访问权限.我需要重定向未经授权的用户(例如,用户尝试删除没有删除访问级别的发票)以访问被拒绝的页面.

自定义属性正在运行.但是在未经授权的用户访问的情况下,浏览器中没有显示任何内容.

控制器代码.

public class InvoiceController : Controller
{
    [AuthorizeUser(AccessLevel = "Create")]
    public ActionResult CreateNewInvoice()
    {
        //...

        return View();
    }

    [AuthorizeUser(AccessLevel = "Delete")]
    public ActionResult DeleteInvoice(...)
    {
        //...

        return View();
    }

    // more codes/ methods etc.
}
Run Code Online (Sandbox Code Playgroud)

自定义属性类代码.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to …
Run Code Online (Sandbox Code Playgroud)

authorization custom-attributes asp.net-mvc-4

22
推荐指数
1
解决办法
6万
查看次数