我使用下面的类来控制我的 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/