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

NSwag生成API代码时,如何将DateTimeOffset替换为DateTime?

解决NSwag生成代码时DateTimeOffset转DateTime的问题

API开发中使用NSwag生成客户端代码时,MeasurementTimeStamp字段被生成为System.DateTimeOffset类型,但实际API返回的Response类中该字段为DateTime类型,需要将生成的字段类型改为System.DateTime。

当前生成的代码

[Newtonsoft.Json.JsonProperty("measurementTimeStamp", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.DateTimeOffset MeasurementTimeStamp { get; set; }

API响应类

public class Response {
    public DateTime MeasurementTimeStamp { get; set; }
}

期望生成的代码

[Newtonsoft.Json.JsonProperty("measurementTimeStamp", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.DateTime MeasurementTimeStamp { get; set; }

解决方法

方法1:全局修改NSwag配置

在NSwag配置文件(如nswag.json)的CSharpClientGeneratorSettings节点中,添加或修改dateTimeType配置为System.DateTime,全局将所有日期时间字段映射为DateTime类型:

{
  "runtime": "Net60",
  "documentGenerator": {
    "fromDocument": {
      "url": "https://your-api-url/swagger/v1/swagger.json",
      "output": null
    }
  },
  "codeGenerators": {
    "csharp": {
      "dateTimeType": "System.DateTime",
      // 保留其他原有配置
    }
  }
}

方法2:针对单个字段修改

若仅需修改特定字段,通过自定义Schema处理器实现:

  1. 创建Schema处理器类:
public class DateTimeSchemaProcessor : ISchemaProcessor
{
    public void Process(SchemaProcessorContext context)
    {
        if (context.TypeName == "Response" && 
            context.PropertyName == "measurementTimeStamp")
        {
            context.Property.Type = new JsonSchemaType(typeof(DateTime));
            context.Schema.Format = null;
        }
    }
}
  1. 在代码生成逻辑中注册该处理器:
var document = await OpenApiDocument.FromUrlAsync("https://your-api-url/swagger/v1/swagger.json");
var settings = new CSharpClientGeneratorSettings();
settings.SchemaProcessors.Add(new DateTimeSchemaProcessor());

var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();

方法3:命令行参数指定

使用NSwag命令行生成代码时,添加/dateTimeType:DateTime参数:

nswag swagger2csclient /input:swagger.json /output:Client.cs /dateTimeType:DateTime

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:07:48