You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.Net Core如何在模型验证前自动修剪字符串并支持指定属性忽略修剪

实现步骤

1. 定义IgnoreTrim特性

首先创建标记用的[IgnoreTrim]特性,用于标识不需要修剪的字符串属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class IgnoreTrimAttribute : Attribute
{
}

2. 实现全局自动修剪过滤器

通过全局Action过滤器实现所有模型的自动修剪逻辑,该逻辑会在Action执行前触发,自动处理所有传入的模型参数:

using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;

public class AutoTrimStringFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // 遍历所有请求绑定的参数
        foreach (var (paramName, argument) in context.ActionArguments)
        {
            if (argument == null) continue;
            // 修剪参数中的字符串属性
            TrimStringProperties(argument);
            // 清空原有验证结果,用修剪后的模型重新验证
            context.ModelState.Clear();
            context.TryValidateModel(argument, paramName);
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // 无需处理Action执行后的逻辑
    }

    private void TrimStringProperties(object obj)
    {
        if (obj == null) return;
        Type objType = obj.GetType();
        // 跳过值类型、字符串本身的处理
        if (objType.IsValueType || objType == typeof(string)) return;

        // 获取类型的所有公共实例属性
        PropertyInfo[] properties = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in properties)
        {
            // 仅处理可读可写的字符串类型属性
            if (prop.PropertyType != typeof(string) || !prop.CanRead || !prop.CanWrite)
                continue;
            // 跳过标记了[IgnoreTrim]的属性
            if (prop.IsDefined(typeof(IgnoreTrimAttribute), inherit: false))
                continue;

            string originalValue = (string)prop.GetValue(obj);
            if (!string.IsNullOrWhiteSpace(originalValue))
            {
                prop.SetValue(obj, originalValue.Trim());
            }
            // 可选逻辑:如果原字符串为全空格,修剪为空白字符串
            // else if (originalValue != null) prop.SetValue(obj, string.Empty);
        }
    }
}

如果需要支持嵌套DTO、集合类参数的修剪,可以自行扩展TrimStringProperties方法,增加递归处理逻辑即可。

3. 注册全局过滤器

在项目启动配置中注册该过滤器,使其全局生效:

ASP.NET Core 6+ (Program.cs)

builder.Services.AddControllers(options =>
{
    options.Filters.Add<AutoTrimStringFilter>();
});

ASP.NET Core 3.1/5 (Startup.cs ConfigureServices方法)

services.AddControllers(options =>
{
    options.Filters.Add<AutoTrimStringFilter>();
});

效果说明

完成上述配置后,所有控制器Action绑定的模型中,字符串属性默认会自动修剪首尾空格,仅需要给不需要修剪的属性加上[IgnoreTrim]标记即可跳过处理,完全无需修改原有Action的代码。

内容的提问来源于stack exchange,提问作者Mohammad Barbast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:15:04