我建议您使用自定义[Authorize]
属性处理此问题。举个例子:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not even authenticated => we can't get much further
return false;
}
// At this stage we know that there's an authneticated user
// let's see who he is by fecthing his username
string username = httpContext.User.Identity.Name;
RouteData rd = httpContext.Request.RequestContext.RouteData;
// Now, let's read the companyId and blogId parameters that he sent
// into the request and ensure that he is not cheating on us
string companyId = rd.Values["companyId"] as string;
string blogId = rd.Values["blogId"] as string;
if (string.IsNullOrEmpty(companyId) || string.IsNullOrEmpty(blogId))
{
// One of the required parameters were not supplied when the action was invoked
// => we can't get much further
return false;
}
return IsOwner(username, companyId, blogId);
}
private bool IsOwner(string username, string companyId, string blogId)
{
// TODO: you know what to do here:
// check with your data store or wherever you have stored this info
throw new NotImplementedException();
}
}
现在你可以用这个属性来装饰你的控制器/动作:
[MyAuthorize]
public ActionResult Edit(string companyId, string blogId)
{
// if we got that far it means that the user is authorized to edit this blog post
// and we could allow him to see the edit view
EditViewModel model = ...
return View(model);
}
当然,为了确保用户不会在 POST 操作中欺骗您,您还可以使用以下属性对其进行装饰:
[MyAuthorize]
[HttpPost]
public ActionResult Edit(EditViewModel model)
{
// if we got that far it means that the user is authorized to edit this blog post
// and we could go ahead and perform the necessary update
....
}