首页 .NET/Web NETCoreAPI 自定义401和异常显示内容(JWT认证、Cookie Base认证失败显示内容)

NETCoreAPI 自定义401和异常显示内容(JWT认证、Cookie Base认证失败显示内容)

作者:胡同里的砖头 围观群众:240 更新于:2024-01-16

1.新建一个Api接口统一返回类ApiResult.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Jom.WebApi.Config
{
public class ApiResult
{
public bool Success { get; set; } = true;
public string Msg { get; set; } = "";
public string Type { get; set; } = "";
public object Data { get; set; } = "";
public object DataExt { get; set; } = "";
}
}
2.建立中间件ErrorHandlingMiddleware.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Jom.WebApi.Config
{
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;

public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}

public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
var statusCode = context.Response.StatusCode;
if (ex is ArgumentException)
{
statusCode = 200;
}
await HandleExceptionAsync(context, statusCode, ex.Message);
}
finally
{
var statusCode = context.Response.StatusCode;
var msg = "";
if (statusCode == 401)
{
msg = "未授权";
}
else if (statusCode == 404)
{
msg = "未找到服务";
}
else if (statusCode == 502)
{
msg = "请求错误";
}
else if (statusCode != 200)
{
msg = "未知错误";
}
if (!string.IsNullOrWhiteSpace(msg))
{
await HandleExceptionAsync(context, statusCode, msg);
}
}
}
     //异常错误信息捕获,将错误信息用Json方式返回
private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
{
var result = JsonConvert.SerializeObject(new ApiResult() { Success=false,Msg=msg,Type= statusCode.ToString() });
context.Response.ContentType = "application/json;charset=utf-8";
return context.Response.WriteAsync(result);
}
}
  //扩展方法
public static class ErrorHandlingExtensions
{
public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ErrorHandlingMiddleware>();
}
}
}
 3.最后只要在Startup.cs或Program.cs中添加引用using Jom.WebApi.Config;
使用扩展方法ErrorHandlingExtensions()使用错误码处理中间件。
//请求错误提示配置
app.UseErrorHandling();
 最后就完成了自定义401页面内容,同时还可以定义其他状态码如403,404,502,503等等,同时api接口报异常也将转化为特定的JSON格式。

postman中请求返回

  • 本文标题: NETCoreAPI 自定义401和异常显示内容(JWT认证、Cookie Base认证失败显示内容)
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8