从Action方法

时间:2016-11-01 17:59:01

标签: asp.net-mvc-4 authorize

[Authorize]
        public ActionResult Delete(string id= null)
        {
            UserDetail userdetail = db.UserDetails.Find(id);
            db.UserDetails.Remove(userdetail);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

此Delete方法仅适用于授权用户。对于未经授权的用户,它显示服务器错误 如何在这种情况下显示自定义授权错误消息,以便它可以是用户友好的错误消息。

1 个答案:

答案 0 :(得分:0)

您可以创建自定义授权

  public class CustomAuthorizationAttribute : AuthorizeAttribute
    {
          protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {

            if (request.IsAjaxRequest())
            {
                // If the request is ajax request, replace with PartialViewResult
                filterContext.Result = new PartialViewResult
                {
                    ViewData = null;//pass whatever,
                    TempData = null;//pass whatever,
                    ViewName = "_partialView"; // whatever partialview
                };
            }

            if (request.IsJsonRequest())
            {
                filterContext.Result = new JsonResult
                {
                    Data = "Nice try buddy ;)";
                };
            }            

 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    controller = "Account",
                    action = "Logon",
                    ReturnUrl = filterContext.HttpContext.Request.RawUrl
                }));
        }
}