溪客(编程代码) 溪客(编程代码)

  • 今天是2025年05月15日 Thursday
  • 首页
  • 知识
  • 网址
  • AI助手

Dotnet

首页 / 知识 / Dotnet
  • 日志
    • logger-级别
  • 数字
    • 数字转哈希
    • 数字后缀
    • 数字范围
  • 时间
    • 时间戳
    • 时间比较
    • 时间-周
    • 计算耗时
  • Xml
    • 什么是Xml
    • XmlDocument的使用
  • aspnet
    • cookie登入登出
    • cookie指定加密的Key
    • 允许跨域
    • WebAPI接收未知参数
    • WebAPI错误默认输出
    • WebAPI使用NewtonsoftJson
    • 使用System.Printing
    • JWT验证错误_升级类库导致
  • CookBook
    • 性能优化
    • 计算地图距离
    • Powershell
    • HttpClient示例
    • HttpWebRequest-Post
    • 雪花Id
    • Directory.GetFiles
    • 获取当前目录
    • 汉字首字母排序_兼容重庆_莞
    • 指定系统的语言(中文)
    • 关于四舍五入
  • 学习
    • 感叹号的作用
    • 栈内存_堆内存.html
    • GetCallingAssembly_GetEntryAssembly_GetExecutingAssembly
  • StackExchange.Redis
    • Cookbook
    • 基础用法
    • 配置
    • 流水线与多路复用
    • 键、值和频道
    • 事务
    • 事件
    • 发布订阅
    • 流
    • 命令
    • 性能分析
    • 脚本
    • 测试
    • Thread Theft

WebAPI错误默认输出

Controller有时候会默认触发一些错误,例如model中配置了Required,没传值会触发错误,且不会进入Action,如果想接管这个错误,可使用配置全局来实现,如下所示

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            var errorMessage = context.ModelState.Values.FirstOrDefault()?.Errors.FirstOrDefault()?.ErrorMessage;
            return new Microsoft.AspNetCore.Mvc.JsonResult(APIResult.CreateError(0, errorMessage));

        };
    })


© 2022 - 溪客(编程代码) - 粤ICP备10217501号 CCBot/2.0 (https://commoncrawl.org/faq/)