[授权]失败后显示404错误页面 [英] Show 404 error page after [Authorize] failure

查看:99
本文介绍了[授权]失败后显示404错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动作,我只想限制为管理员"角色.我是这样做的:

I have an action I want to restrict only to role "Admin". I did it like this:

[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)

手动进入Controller/Edit/1路径后,我被重定向到登录页面.好吧,这也许还不错,但是我想显示404而不是它,并尝试坚持使用属性.有可能吗?

After manually going under Controller/Edit/1 path I'm redirected to login page. Well, that isn't bad maybe, but I want to show 404 instead of it and try to stick using attributes for it. Is that possible?

推荐答案

有可能吗?

Is that possible?

当然,您可以编写自定义的授权属性:

Sure, you could write a custom authorize attribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/Shared/401.cshtml"
        };
    }
}

然后使用它:

[MyAuthorize(Roles = "Admin")]
public ActionResult Edit(int id)

备注:如果未授权用户而不是未找到文件的404,则您可能希望显示401或403页面.

Remark: you probably want to show a 401 or 403 page if the user is not authorized instead of 404 which is for file not found.

这篇关于[授权]失败后显示404错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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