Asp.net mvc MVC自定义授权属性以验证请求
我有一个带有Jquery的UI,它使用Ajax请求调用MVC 我想根据userProfile(保存帐号、ID等的自定义类)验证每个请求 是否有人可以建议是否可以创建自定义授权属性来验证请求和用户配置文件是否相同 然后,我想做如下工作:Asp.net mvc MVC自定义授权属性以验证请求,asp.net-mvc,asp.net-mvc-3,Asp.net Mvc,Asp.net Mvc 3,我有一个带有Jquery的UI,它使用Ajax请求调用MVC 我想根据userProfile(保存帐号、ID等的自定义类)验证每个请求 是否有人可以建议是否可以创建自定义授权属性来验证请求和用户配置文件是否相同 然后,我想做如下工作: [AuthorizeUser] public ActionResult GetMyConsumption(string accountNumber) { ..... return View(); } 您可以编写自定义授权属性: public class
[AuthorizeUser]
public ActionResult GetMyConsumption(string accountNumber)
{
.....
return View();
}
您可以编写自定义授权属性:
public class AuthorizeUserAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
// The user is not authorized => no need to continue
return false;
}
// At this stage we know that the user is authorized => we can fetch
// the username
string username = httpContext.User.Identity.Name;
// Now let's fetch the account number from the request
string account = httpContext.Request["accountNumber"];
// All that's left is to verify if the current user is the owner
// of the account
return IsAccountOwner(username, account);
}
private bool IsAccountOwner(string username, string account)
{
// TODO: query the backend to perform the necessary verifications
throw new NotImplementedException();
}
}
如果您愿意解析请求表单/查询字符串中的数据并验证它们,那么这是可能的。您可以在自定义授权属性中完全访问httpContext。如果是POST,则必须假设表单中必须存在变量“accountNumber”,如果是GET,则必须存在查询字符串。参数绑定(将请求中的数据映射到操作中的参数)将围绕OnActionExecuting方法进行,该方法为后授权。Yep accountID将被传递。请检查(AuthorizeCore vs OnAuthorize),下面有人正在查看一些请求数据(预算)以确定用户是否被授权: