示例
新建TokenAuthorizationFilter.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CRUDExample.Filters.AuthorizationFilters
{
public class TokenAuthorizationFilter : IAsyncAuthorizationFilter
{
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (context.HttpContext.Request.Cookies.ContainsKey("Auth-Key") == false)
{
context.Result = new StatusCodeResult(StatusCodes.Status401Unauthorized);
return;
}
if (context.HttpContext.Request.Cookies["Auth-Key"] != "A100")
{
context.Result = new StatusCodeResult(StatusCodes.Status401Unauthorized);
return;
}
}
}
}
新建TokenResultFilter.cs(添加缓存)
using Microsoft.AspNetCore.Mvc.Filters;
namespace CRUDExample.Filters.ResourceFilters
{
public class TokenResultFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
context.HttpContext.Response.Cookies.Append("Auth-Key", "A100");
await next();
}
}
}
Edit Action HttpPost添加验证的Filter,Edit Action HttpGet添加缓存的Filter
[HttpPost]
[Route("[action]/{personId}")] //persons/edit/1
[TypeFilter(typeof(TokenAuthorizationFilter))]
public async Task<IActionResult> Edit(PersonUpdateRequest personUpdateRequest)
[HttpGet]
[Route("[action]/{personId}")] //persons/edit/1
[TypeFilter(typeof(TokenResultFilter))]
public async Task<IActionResult> Edit(Guid personId)
运行程序后可以正常Edit,如果去掉缓存Filter,点击Update后显示如下
Gitee获取源码:
https://gitee.com/huang_jianhua0101/asp.-net-core-8.git
标签:Task,Edit,Filter,context,252,async,public,Authorization From: https://blog.csdn.net/KevinHuang2088/article/details/139451388