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

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

问题描述

修改称为控制器的方法中,用户可以编辑数据,他们已经像这样创造...

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
}

此方法效果但罚款是有点乱摆在每个控制器编辑方法。每个表总是有一个用户名所以,如果有通过自动执行此一个更简单的方法,我在想,一个 [授权] 属性或一些其他机制,使code清洁。

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.

推荐答案

是的,你可以做到这一点通过自定义授权属性:

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天全站免登陆