我使用下面的类来控制我的 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 中实现相同的结构时,我无法到达已初始化的控制器实例。有什么办法可以得到那个实例。
使用 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
}
}