首页 > 解决方案 > 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 方法均未调用。你能解释一下这里有什么问题吗?

标签: c#asp.net-coreauthorizationwebapi

解决方案


您正在使用ASP.NET Core 未使用的命名空间AuthorizeAttribute。改为System.Web.Http实现接口IAuthorizationFilter

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //...
    }
}

推荐阅读