ASP.NET MVC 属性只允许用户编辑他/她自己的内容 [英] ASP.NET MVC Attribute to only let user edit his/her own content

查看:13
本文介绍了ASP.NET MVC 属性只允许用户编辑他/她自己的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Edit 的控制器方法,用户可以在其中编辑他们创建的数据......

I have a controller method called Edit in which the user can edit data they had created like so ...

public ActionResult Edit(int id)
{
    Submission submission = unit.SubmissionRepository.GetByID(id);
    User user = unit.UserRepository.GetByUsername(User.Identity.Name);

    //Make sure the submission belongs to the user
    if (submission.UserID != user.UserID)
    {
        throw new SecurityException("Unauthorized access!");
    }

    //Carry out method
}

这个方法很好用,但是把每个控制器的 Edit 方法都放进去有点麻烦.每个表总是有一个 UserID,所以我想知道是否有一种更简单的方法可以通过 [Authorize] 属性或其他一些机制来使代码更清晰.

This method works fine however it is a little messy to put in every controller Edit method. Each table always has a UserID so I was wondering if there was an easier way to automate this via an [Authorize] Attribute or some other mechanism to make the code cleaner.

推荐答案

是的,您可以通过自定义 Authorize 属性来实现:

Yes, you could achieve that through a custom Authorize attribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            return false;
        }

        var rd = httpContext.Request.RequestContext.RouteData;

        var id = rd.Values["id"];
        var userName = httpContext.User.Identity.Name;

        Submission submission = unit.SubmissionRepository.GetByID(id);
        User user = unit.UserRepository.GetByUsername(userName);

        return submission.UserID == user.UserID;
    }
}

然后:

[MyAuthorize]
public ActionResult Edit(int id)
{
    // Carry out method
}

假设您需要将此提交实例提供给我们作为操作参数提取到自定义属性中的提交实例,以避免再次访问数据库,您可以执行以下操作:

and let's suppose that you need to feed this submission instance that we fetched into the custom attribute as action parameter to avoid hitting the database once again you could do the following:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            return false;
        }

        var rd = httpContext.Request.RequestContext.RouteData;

        var id = rd.Values["id"];
        var userName = httpContext.User.Identity.Name;

        Submission submission = unit.SubmissionRepository.GetByID(id);
        User user = unit.UserRepository.GetByUsername(userName);

        rd.Values["model"] = submission;

        return submission.UserID == user.UserID;
    }
}

然后:

[MyAuthorize]
public ActionResult Edit(Submission model)
{
    // Carry out method
}

这篇关于ASP.NET MVC 属性只允许用户编辑他/她自己的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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