gpt4 book ai didi

asp.net-mvc-3 - "user may do X is user owns object Y": Implement logic in Model Validation or Controller logic?

转载 作者:行者123 更新时间:2023-12-02 05:07:40 25 4
gpt4 key购买 nike

例如,考虑逻辑“用户只能编辑或删除该用户发表的评论”。

My Controller Actions会重复检查当前登录用户是否可以影响评论的逻辑。示例

[Authorize]
public ActionResult DeleteComment(int comment_id)
{
var comment = CommentsRepository.getCommentById(comment_id);
if(comment == null)
// Cannot find comment, return bad input
return new HttpStatusCodeResult(400);
if(comment.author != User.Identity.Name)
// User not allowed to delete this comment, return Forbidden
return new HttpStatusCodeResult(403);
// Error checking passed, continue with delete action
return new HttpStatusCodeResult(200);
}

当然,我可以将该逻辑捆绑在一个方法中,这样我就不会复制/粘贴该片段;但是,将该代码从 Controller 中取出并将其放入 ValidationAttribute 中可以使我的 Action 更小并且更容易为其编写测试。示例

public class MustBeCommentAuthorAttribute : ValidationAttribute
{
// Import attribute for Dependency Injection
[Import]
ICommentRepository CommentRepository { get; set; }

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int comment_id = (int)value;
var comment = CommentsRepository.getCommentById(comment_id);
if(comment == null)
return new ValidationResult("No comment with that ID");
if(comment.author != HttpContext.Current.User.Identity.Name)
return new ValidationResult("Cannot edit this comment");
// No errors
return ValidationResult.Success;
}
}

public class DeleteCommentModel
{
[MustBeCommentAuthor]
public int comment_id { get; set; }
}

模型验证是否适合这项工作?我喜欢从 Controller Action 中消除这种担忧;但在这种情况下,它可能会使事情进一步复杂化。当您认为此操作是 RESTful API 的一部分并且需要根据 ModelState 中的验证错误返回不同的 HTTP 状态代码时,尤其如此。

在这种情况下是否有“最佳实践”?

最佳答案

就我个人而言,我认为它看起来不错,但您会被注释冲昏头脑。我认为这不属于您的表示层,应该由您的服务层处理。

我想说的是:

[Authorize] 
public ActionResult DeleteComment(int comment_id)
{
try
{
var result = CommentsService.GetComment(comment_id, Auth.Username);

// Show success to the user
}
catch(Exception e)
{
// Handle by displaying relevant message to the user
}
}

关于asp.net-mvc-3 - "user may do X is user owns object Y": Implement logic in Model Validation or Controller logic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9333916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com