记一个webapi返回值的处理

using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

namespace CQRS.WebAPI.Middlewares;

public class GlobalExceptionHandlingMiddleware : IMiddleware
{
    private readonly ILogger<GlobalExceptionHandlingMiddleware> _logger;

    public GlobalExceptionHandlingMiddleware( 
        ILogger<GlobalExceptionHandlingMiddleware> logger)
    {
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try{
            await next(context);
        }
        catch(Exception e)
        {
            _logger.LogError(e.Message);

            ProblemDetails problem = new()
            {
                Status = (int)HttpStatusCode.InternalServerError,
                Type = "Server error",
                Title = "Server error",
                Detail = "An internal server has occurred"
            };
            string json = JsonSerializer.Serialize(problem);

            context.Response.ContentType = "application/json";

            await context.Response.WriteAsync(json);
        }
    }
}

 其他:

接口日志应该使用中间件记录,.net6已经有官方实现了
https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/http-logging

一个封装返回值的类:

public class ApiResponse<T>
{
    public bool Success { get; set; }
    public T Data { get; set; }
    public string ErrorMessage { get; set; }
    public string ErrorCode { get; set; }

    public static ApiResponse<T> Success(T data)
    {
        return new ApiResponse<T>
        {
            Success = true,
            Data = data
        };
    }

    public static ApiResponse<T> Fail(string errorMessage, string errorCode = "")
    {
        return new ApiResponse<T>
        {
            Success = false,
            ErrorMessage = errorMessage,
            ErrorCode = errorCode
        };
    }
}

 

posted @ 2023-06-27 22:27  vba是最好的语言  阅读(18)  评论(0编辑  收藏  举报