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

C# API接收PostData时保留字type被转@type的解决方案求助

解决C# API请求中type字段被转为@type的问题

这个问题我之前也碰到过,核心原因是type是C#的保留关键字,当你在模型类里定义同名属性时,编译器要求你用@Type来规避关键字冲突,但默认序列化时会把@也带进去,导致字段变成@type,和API要求的type不匹配。下面给你几个可行的解决办法:

方法1:用序列化特性指定字段名(推荐)

根据你项目使用的JSON序列化库不同,选择对应的特性:

如果你用的是Newtonsoft.Json(Json.NET)

在模型的属性上添加[JsonProperty("type")]特性,强制指定序列化后的字段名为type:

public class TransferRequest
{
    public string currency { get; set; }
    public string amount { get; set; }
    
    [JsonProperty("type")]
    public string Type { get; set; } // 这里即使属性名带@也没关系,特性会覆盖输出
    // 或者直接写:public string @Type { get; set; } 效果一样
}

如果你用的是System.Text.Json(.NET Core/.NET 5+ 默认库)

使用[JsonPropertyName("type")]特性:

using System.Text.Json.Serialization;

public class TransferRequest
{
    public string currency { get; set; }
    public string amount { get; set; }
    
    [JsonPropertyName("type")]
    public string Type { get; set; }
}

方法2:手动构造匿名对象序列化(无需修改模型)

如果不想修改现有模型,可以直接构造匿名对象来生成正确的JSON:

var requestData = new 
{
    currency = "BTC",
    amount = "0.00049659",
    type = "bankToExchange"
};

// 然后序列化这个匿名对象发送请求
string json = JsonSerializer.Serialize(requestData); // System.Text.Json
// 或者用Newtonsoft:string json = JsonConvert.SerializeObject(requestData);

匿名对象不受C#关键字限制,序列化后会直接输出type字段,和Postman里的请求内容完全一致。

方法3:配置序列化全局规则(批量处理)

如果你有很多地方需要处理关键字字段,可以全局配置序列化器,自动移除属性名前的@:

// 在Program.cs(.NET 6+)中添加全局配置
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        // 自定义命名策略,移除属性名的@前缀
        options.JsonSerializerOptions.PropertyNamingPolicy = new RemoveAtPrefixNamingPolicy();
    });

// 自定义命名策略实现
public class RemoveAtPrefixNamingPolicy : JsonNamingPolicy
{
    public override string ConvertName(string name)
    {
        return name.StartsWith("@") ? name.Substring(1) : name;
    }
}

不过这种方式相对复杂,除非有大量类似需求,否则推荐前两种更直接的方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:17:55