using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization.Infrastructure; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WeTax.CommonLibrary.Models.Enum; namespace MerchantsApi.Filters { public class MerchantAuthorizeAttribute : AuthorizeFilter { private static AuthorizationPolicy _policy_ = new AuthorizationPolicy(new[] { new DenyAnonymousAuthorizationRequirement() }, new string[] { }); public MerchantAuthorizeAttribute() : base(_policy_) { } public override async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (string.IsNullOrEmpty(context.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "userid")?.Value)) { context.Result = new JsonResult(new WeTax.CommonLibrary.Models.WebApiResult(ApiResultCode.Fail, "请登录")); } await base.OnAuthorizationAsync(context); } } }
services.AddMvc(options => { options.Filters.Add<MerchantAuthorizeAttribute>(); //options.Filters.Add<AuthExceptionFilter>(); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);