Asp.net MVC授权属性,重定向到自定义的"没有权利和QUOT;页 [英] Asp.net MVC Authorize attribute, redirect to custom "no rights" page

查看:95
本文介绍了Asp.net MVC授权属性,重定向到自定义的"没有权利和QUOT;页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Asp.net MVC2不带重定向到登录页面响应302 认证时,用户没有权限。

Asp.net MVC2 does redirect to login page with response 302 when authenticated user has no rights.

我想分成两个动作


  1. 如果用户没有通过验证,然后做它,重定向到登录页面。

  2. 如果用户进行身份验证,但没有所需的权限,然后返回相应的HTTP状态code,且没有权利花花公子页面。

有没有办法做到这一点?还是我做错了什么与授权和形式的认证?我唯一​​能想到的办法是通过编写定制的授权属性,我希望避免的。

Is there any way to do it? Or am I doing something wrong with authorize and form authentication? Only way I can think of is by writing custom authorize attribute, which I want to avoid.

推荐答案

您可以写这样的自定义过滤器属性:

You could write custom filter attribute like this:

public class CustomAuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity == null || !filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" +
                filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
            }

            //Check user right here
            if (userNotRight)
            {
                filterContext.HttpContext.Response.StatusCode = 302;
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }

和控制器中使用它:

[CustomAuthorize]
public class HomeController : Controller
{

}

这篇关于Asp.net MVC授权属性,重定向到自定义的"没有权利和QUOT;页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆