dotnet core 自定义Attribute
2021-03-20 07:26
标签:reg gis city register namespace requests some name where 使用dotnet core 2.1 然後就可以使用Permission 在startup的configureservice添加 dotnet core 自定义Attribute 标签:reg gis city register namespace requests some name where 原文地址:https://www.cnblogs.com/hwxing/p/12737356.html自定義Attribute
第一種
using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
namespace MyProject.Utils
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class PermissionAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _Permission;
private IConfiguration _config;
public PermissionAttribute(string Permission)
{
_Permission = Permission;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
this._config = (IConfiguration)context.HttpContext.RequestServices.GetService(typeof(IConfiguration));
var tem = _config["Temperature:city"];
var user = context.HttpContext.User;
if(!user.Identity.IsAuthenticated)
{
context.Result = new UnauthorizedResult();
return;
}
// you can also use registered services
// var someService = context.HttpContext.RequestServices.GetService
[Route("api/[controller]")]
[ApiController,Authorize,Permission("123")]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult
第二種
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
namespace MyProject.Utils
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class PermissionAttribute : AuthorizeAttribute
{
public string Name { get; }
public PermissionAttribute(string name) : base("Permission")
{
Name = name;
}
}
public abstract class AttributeAuthorizationHandler
services.AddSingleton