未经授权时覆盖重定向URL的方法(.NET Core)

3
基本上我想要实现的是像这样的功能:
[AllowAnonymous]
    public ActionResult MyAction(string id)
    {
        if (Request.IsAuthenticated)
        {
            //do stuff
            return View();
        }
        //if we come here, redirect to my custom action
        return RedirectToAction("Action","Controller", new {@id=id});
    } 

但是我正在尝试使用自定义属性来实现同样的功能,类似于这样:

[Authorize(RedirectIfNotAuthorized="~/Controller/Action/id")]
    public ActionResult MyAction(string id)
    {

        //do stuff
        return View();
    } 

根据我所了解的,通过更改Asp.net Identity的配置,可以将默认的url("/Account/Login")更改为其他url。然而这并不是我想要的。我想在某些特定情况下重定向到另一个url。
背景是,当用户因长时间不活动而注销登录时,有些重定向url是不需要的。比如说,一个用户正在从类似("~/Files/Pdf/123")的url下载文件,但是却被注销了。当他重新登录后,我不希望他被重定向到这个url。
1个回答

3
您需要自定义属性:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Attributes
{
    public class AuthAttribute : ActionFilterAttribute
    {
        private readonly string _action;
        private readonly string _controller;
        private readonly string _role;

        public AuthAttribute(string action, string controller, string role)
        {
            _action = action;
            _controller = controller;
            _role = role;
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.User.IsInRole(_role))
            {
                filterContext.Result = new RedirectToRouteResult(new {action = _action, controller = _controller});
            }
            else
            {
                base.OnResultExecuting(filterContext);
            }
        }
    }
}

使用方法:

[Auth("Test", "Home", "Admin")]
public IActionResult Index()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接