ASP.NET Core 404 Middleware

2021年8月12日 2652点热度 0人点赞 0条评论
内容目录

Middleware example:

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 Middleware
    /// </summary>
    public class NotFoundMiddleware
    {
        // JSON serialization settings
        private static readonly JsonSerializerOptions JsonSetting = new JsonSerializerOptions()
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = true
        };

        private readonly RequestDelegate _next;

        /// <summary>
        /// 404 Middleware
        /// </summary>
        /// <param name="next">Delegate</param>
        public NotFoundMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// Delegate
        /// </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 = $"The requested address {context.Request.Path} does not exist",
                Data = context.Request.Path
            };
            await context.Response.WriteAsync(JsonSerializer.Serialize(result, JsonSetting));
        }
    }
}

Using middleware:

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseMiddleware<NotFoundMiddleware>();
            }

痴者工良

高级程序员劝退师

文章评论