好.所以我有一个问题,我需要在控制器操作中进行一些授权检查.
有授权角色,但可能存在某人有TypeOnePayment,但没有TypeTwo
[Authorize(Roles = "TypeOnePayment;TypeTwoPayment")]
public ActionResult EnterRevenue(PaymentType payment)
{
payment = "TypeOne"; // This exists for show only.
var permission = string.Concat(payment,"Permission");
if (!SecurityUtility.HasPermission(permission))
{
return View("Unauthorized", "Error");
}
return this.PartialView("_EnterRevenue");
}
Run Code Online (Sandbox Code Playgroud)
但由于这是返回局部视图,因此"错误"屏幕仅出现在页面的局部视图部分中.有没有办法重定向到一个全新的页面?
编辑:通过ajax调用检索EnterRevenue.所以只是返回了html,它被放置在它被调用的视图中.
您可以重定向到其他一些操作:
public ActionResult EnterRevenue
{
if (!SecurityUtility.HasPermission(permission))
{
return View("Unauthorized", "Error");
}
return RedirectToAction("NotAuthorized","Error");
}
Run Code Online (Sandbox Code Playgroud)
假设我们有一个返回普通视图的ErrorController动作NotAuthorized,显示您无权查看此页面.
如果您需要检查每个操作,那么您需要实现自定义操作过滤器属性,在该属性中您必须检查它是否是正常请求重定向,否则返回staus作为json并从客户端重定向.在访问页面之前,请参阅asp.net mvc检查用户是否获得授权
这是一大堆代码:
public class AuthorizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string actionName = filterContext.ActionDescriptor.ActionName;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
if (filterContext != null)
{
HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
var userSession = objHttpSessionStateBase["userId"];
if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession))
{
objHttpSessionStateBase.RemoveAll();
objHttpSessionStateBase.Clear();
objHttpSessionStateBase.Abandon();
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.Result = new JsonResult { Data = "LogOut" };
}
else
{
filterContext.Result = new RedirectResult("~/Home/Index");
}
}
else
{
if (!CheckAccessRight(actionName, controllerName))
{
string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在这样的行动中使用它:
[Authorization]
public ActionResult EnterRevenue
{
return this.PartialView("_EnterRevenue");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14195 次 |
| 最近记录: |