我的目标是在抛出Unathorized事件时在视图上显示模式对话框。我已经覆盖了我的自定义AuthorizedAttribute的OnAuthorization方法,如下文所示:
ASP.NET MVC - How to show unauthorized error on login page?
但问题是TempData被发送到未经授权的控制器(ClientController),这不是理想的行为。
我需要的是:致电Home / Index / ToClientes,当它试图让客户/索引在Home / Index上显示模态对话框时,告知用户未经授权的事件。
[HttpPost]
public ActionResult ToClientes()
{
return RedirectToAction("Index", "Client");
}
目前在ClientController中读取TempData我需要在HomeController上读取它以显示解释错误的模态弹出视图。
My Overrride OnAuthorization方法类似于引用帖子
上的方法public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private bool _isAuthorized;
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
_isAuthorized = base.AuthorizeCore(httpContext);
return _isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if(!_isAuthorized)
{
filterContext.Controller.TempData.Add("RedirectReason", "Unauthorized");
}
}
}
无论如何将TempData发送到调用该函数的控制器而不是生成onAuthorization方法的控制器?或者,在引发未经授权的事件时,还有其他更简单的方法来显示模态弹出窗口吗?
答案 0 :(得分:0)
我找到了实现目标的方法。
我使用Session在HandleUnauthorizedRequest中的自定义AuthorizeAtributte中存储有关Unauthorized事件的信息
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.HttpContext.Session["OpenAuthorizationPopup"] = "true";
filterContext.Result = new RedirectResult(filterContext.Controller.TempData["urlOrigen"].ToString());
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
需要filterContext.Result以避免执行未授权函数中的代码。
然后在所有视图的共享布局中我添加了JS代码
@if ((Session["OpenAuthorizationPopup"] ?? "false") == "true")
{
Session["OpenAuthorizationPopup"] = "false";
<script type="text/javascript">
$(document).ready(function () {
$('#myModal').modal('show');
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
}
现在,模式视图仅在未经授权的事件被引发时显示,并显示在生成请求的页面上。