c# - 在未授权 .net core 时覆盖 redirecturl

标签 c# asp.net asp.net-core asp.net-core-mvc

基本上我想要完成的是这样的:

[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。

最佳答案

您需要自定义属性:

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()

关于c# - 在未授权 .net core 时覆盖 redirecturl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46913026/

相关文章:

C# 使类返回其实例而不带函数或变量

c# - 带有时间戳的范围键。使用 DynamoDB 进行查询和分页

c# - EF Include 始终为第一个导航属性生成 INNER JOIN

asp.net-core - .net core 2.0 - 值不能为空。参数名称: key

c# - 如何在 ASP.NET Core 中返回存储为 byte[] 的文件?

c# - Web API 2.0 - 使用 JavaScriptConverter 自定义日期格式

c# - .NET 4.5 HttpTaskAsyncHandler 上传文件

c# - 按另一个内存列表对内存列表进行排序

asp.net - MVC 6 vNext 显示名称属性不起作用

c# - 通过代理使用 KeyVaultClient