是的,您可以通过自定义 Authorize 属性来实现:
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
}
假设您需要将我们提取到自定义属性中的提交实例作为操作参数提供,以避免再次访问数据库,您可以执行以下操作:
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
}