内容目录
中间件示例:
using AuthCenter.Domain.Modules;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AuthCenter.Domain.Middlewares
{
/// <summary>
/// 404 中间件
/// </summary>
public class NotFoundMiddleware
{
// json 序列化配置
private static readonly JsonSerializerOptions JsonSetting = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
private readonly RequestDelegate _next;
/// <summary>
/// 404 中间件
/// </summary>
/// <param name="next">委托</param>
public NotFoundMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// 委托
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
await _next(context);
if (context.Response.StatusCode != 404)
{
return;
}
var result = new ResponseJsonResultModel<string>
{
Code = 404,
Msg = $"所请求的 {context.Request.Path} 地址不存在",
Data = context.Request.Path
};
await context.Response.WriteAsync(JsonSerializer.Serialize(result, JsonSetting));
}
}
}
使用中间件:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseMiddleware<NotFoundMiddleware>();
}
文章评论