c# - AuthorizeAttribute 在 .net 5 web api 中不起作用
问题描述
我正在尝试使用 System.Web.Http.AuthorizeAttribute 实现自定义授权,但它不起作用。我有以下控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApplication2.Helpers;
namespace WebApplication2.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : Controller
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
[CustomAuthorize]
public IEnumerable<WeatherForecast> Get()
{
if (User.Identity.IsAuthenticated)
{
}
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
我创建了自定义授权属性:
using System;
using System.Web.Http.Controllers;
namespace WebApplication2.Helpers
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw new Exception();
}
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
bool isAuthroized = base.IsAuthorized(actionContext);
return isAuthroized;
}
}
}
调用 Get 天气预报时,OnAuthorization 和 IsAuthorized 方法均未调用。你能解释一下这里有什么问题吗?
解决方案
您正在使用ASP.NET Core 未使用的命名空间AuthorizeAttribute
。改为System.Web.Http
实现接口IAuthorizationFilter
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//...
}
}
推荐阅读
- php - 如何链接到页面的特定部分 HTML PHP
- c# - 当后端代码中的简单键值变量工作相同时,为什么要使用 redis 作为缓存层?
- google-apps-script - Google Slides Apps 脚本检索页面中的形状
- python-3.x - 在 KNeighborsClassifier 中使用自定义指标时,我不断收到“TypeError:只有整数标量数组可以转换为标量索引”
- java - JavaFX - 在使用选项卡时将 GUI 拆分为单独的类
- jquery - 通过函数调整电子窗口大小
- scheme - 匹配方案中的括号
- android - 当我使用 adb 显示 /sys/kernel/debug/tracing/available_filter_functions 时没有这样的设备
- python - 初始化以迭代抽象pyomo模型中的集合?
- angular-cli - 运行 ng serve -o 时出现错误