能否隐藏Asp.Net Core 400响应中的C#实现细节?
如何修改Asp.Net Core的400响应,避免暴露C#实现细节
当请求不符合模型验证规则或JSON反序列化失败时,Asp.Net Core默认返回的400响应会包含C#类全限定名等内部实现细节,这类信息无需对外暴露。以下是两种可行的解决方案:
方案一:自定义ProblemDetailsFactory(全局控制)
通过替换默认的ProblemDetailsFactory,可以全局统一处理所有400响应的错误内容,移除C#类型引用:
1. 创建自定义ProblemDetailsFactory类
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.ModelBinding; using System.Diagnostics; using System.Text.RegularExpressions; public class CustomProblemDetailsFactory : ProblemDetailsFactory { private readonly ApiBehaviorOptions _options; public CustomProblemDetailsFactory(ApiBehaviorOptions options) { _options = options ?? throw new ArgumentNullException(nameof(options)); } public override ProblemDetails CreateProblemDetails( HttpContext httpContext, int? statusCode = null, string? title = null, string? type = null, string? detail = null, string? instance = null) { var problemDetails = new ProblemDetails { Status = statusCode, Title = title, Type = type, Detail = detail, Instance = instance, }; ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode ?? 500); return problemDetails; } public override ValidationProblemDetails CreateValidationProblemDetails( HttpContext httpContext, ModelStateDictionary modelStateDictionary, int? statusCode = null, string? title = null, string? type = null, string? detail = null, string? instance = null) { if (modelStateDictionary == null) throw new ArgumentNullException(nameof(modelStateDictionary)); var problemDetails = new ValidationProblemDetails(modelStateDictionary) { Status = statusCode, Type = type, Detail = detail, Instance = instance, }; if (title != null) problemDetails.Title = title; ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode ?? 400); // 清理错误消息中的C#类型引用 foreach (var key in problemDetails.Errors.Keys.ToList()) { var errors = problemDetails.Errors[key].ToList(); for (int i = 0; i < errors.Count; i++) { errors[i] = Regex.Replace(errors[i], @"JSON deserialization for type '([^']+)' was missing required properties, including the following: ", "Missing required properties: "); } problemDetails.Errors[key] = errors.ToArray(); } return problemDetails; } private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int statusCode) { problemDetails.Status ??= statusCode; if (_options.ClientErrorMapping.TryGetValue(statusCode, out var clientErrorData)) { problemDetails.Title ??= clientErrorData.Title; problemDetails.Type ??= clientErrorData.Link; } var traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier; if (traceId != null) problemDetails.Extensions["traceId"] = traceId; } }
2. 在Program.cs中注册自定义工厂
builder.Services.AddControllers(); // 替换默认的ProblemDetailsFactory builder.Services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();
方案二:配置ApiBehaviorOptions(局部/全局)
通过ApiBehaviorOptions的InvalidModelStateResponseFactory属性,直接修改模型验证错误的响应内容:
builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problemDetails = new ValidationProblemDetails(context.ModelState) { Status = StatusCodes.Status400BadRequest, Title = "One or more validation errors occurred.", }; // 清理错误消息中的C#类型信息 foreach (var key in problemDetails.Errors.Keys.ToList()) { var errors = problemDetails.Errors[key].ToList(); for (int i = 0; i < errors.Count; i++) { errors[i] = Regex.Replace(errors[i], @"JSON deserialization for type '([^']+)' was missing required properties, including the following: ", "Missing required properties: "); } problemDetails.Errors[key] = errors.ToArray(); } return new BadRequestObjectResult(problemDetails); }; });
修改后的响应示例
处理后,400响应将不再包含C#类名,示例如下:
{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-71b3ed06990f759c440ed484475b437c-23db588b254e8013-00", "errors": { "$": [ "Missing required properties: messageId" ], "request": [ "The request field is required." ] } }
内容的提问来源于stack exchange,提问作者Ilya Chernomordik
相关产品推荐
相关产品推荐

