c# - 在 AuthorizeAttribute Mvc Core Web Api 中获取 Controller 实例

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

我使用下面的类来控制我的 api 方法请求并设置 BaseController 类的一些属性以在方法中常用。 这个来自 Asp.Net Mvc Web Api

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class AuthUserAttribute : AuthorizeAttribute
{

    private string Action { get; set; }

    public AuthUserAttribute(string action)
    {
        this.Action = action;
    }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        BaseController baseController = httpContext.ControllerContext.Controller as BaseController;
        baseController.someCommenProperty = someValue;
    }
}

但是当我试图在 Asp.Net Mvc Core Api 中实现相同的结构时 我无法到达初始化的 Controller 实例。 我有什么办法可以获得那个实例。

使用 Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using System;
using System.Linq;

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class AuthUserAttribute : AuthorizeAttribute, IAuthorizationFilter
{


    private string Action { get; set; }
    public AuthUserAttribute(string action)
    {
        this.Action = action;
    }



    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // how to get controller instance from context
    }
}

最佳答案

您可以使用context.ActionDescriptor 获取 Controller 的Type 信息。
在授权检查时, Controller 对象可能根本没有被实例化。
您还可以实现IActionFilter 并在其中使用 Controller 实例

public void OnActionExecuting(ActionExecutingContext context)

public void OnActionExecuted(ActionExecutingContext context)

关于c# - 在 AuthorizeAttribute Mvc Core Web Api 中获取 Controller 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747090/

相关文章:

c# - ActionFilterAttribute 中的 GetService 返回 null

asp.net-mvc - ASP.NET Core MVC 应用程序中的总命中/访问者计数器

c# - 尝试在 ActionResult 中返回 HTML 会导致 HTTP 406 错误

c# - 你怎么知道一种语言是否是 "dynamic language"?

c# - 内部声明变量的 T-SQL 参数化查询?

添加到 ASP.NET Core 元素中的 site.css 文件时,CSS 不起作用。但在添加为内联时有效

asp.net - 我是 .NET Core 2.1 MVC 的新手,无法理解一些事情的工作原理

c# - ASP.NET Core文件上传表单绑定(bind)问题

c# - 如何检查 XML 中是否存在特定属性?

c# - Xamarin 表单选择器绑定(bind)