gpt4 book ai didi

asp.net-mvc - MVC 3 - 仅特定用户访问

转载 作者:行者123 更新时间:2023-12-02 14:37:17 24 4
gpt4 key购买 nike

在我的网络应用程序中,注册用户可以添加新内容并稍后进行编辑。我希望只有内容的作者才能编辑它。除了在所有操作方法中手动编写代码来检查登录用户是否与作者相同之外,还有其他聪明的方法可以做到这一点吗?我可以为整个 Controller 使用任何属性吗?

最佳答案

Any attribute that I could use for the whole controller?

是的,您可以使用自定义属性来扩展 Authorize 属性:

public class AuthorizeAuthorAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
// the user is either not authenticated or
// not in roles => no need to continue any further
return false;
}

// get the currently logged on user
var username = httpContext.User.Identity.Name;

// get the id of the article that he is trying to manipulate
// from the route data (this assumes that the id is passed as a route
// data parameter: /foo/edit/123). If this is not the case and you
// are using query string parameters you could fetch the id using the Request
var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string;

// Now that we have the current user and the id of the article he
// is trying to manipualte all that's left is go ahead and look in
// our database to see if this user is the owner of the article
return IsUserOwnerOfArticle(username, id);
}

private bool IsUserOwnerOfArticle(string username, string articleId)
{
throw new NotImplementedException();
}
}

然后:

[HttpPost]
[AuthorizeAuthor]
public ActionResult Edit(int id)
{
... perform the edit
}

关于asp.net-mvc - MVC 3 - 仅特定用户访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10064631/

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