小编m3r*_*ali的帖子

在 AuthorizeAttribute Mvc Core Web Api 中获取控制器实例

我使用下面的类来控制我的 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

使用 Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using …
Run Code Online (Sandbox Code Playgroud)

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

3
推荐指数
1
解决办法
2776
查看次数