c# - Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式

标签 c# asp.net-core asp.net-web-api swagger swagger-ui

我想知道是否有人可以帮助我,我正在尝试更改 swagger UI 中的日期格式

2020-03-07T14:49:48.549Z


07-03-2020T14:49

我正在尝试删除秒并将日期格式放入“dd/MM/yyyy HH:mm”,现在我已经尝试过了
    services.AddControllers()
        .AddNewtonsoftJson(options =>
        {
            var dateConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter
            {
                DateTimeFormat = "dd'/'MM'/'yyyy HH:mm:ss"
            };

            options.SerializerSettings.Converters.Add(dateConverter);
            options.SerializerSettings.Culture = new CultureInfo("en-IE");
            options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
        })

我在网上看到了各种例子,但似乎没有一个有效。

最佳答案

这是一个如下所示的工作演示:

1. Controller :

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpGet]
    public DateTime Get()
    {
        var data = DateTime.Now;
        return data;
    }

    // POST api/<controller>
    [HttpPost]
    public DateTime Post([FromBody]string value)
    {
        var data = DateTime.Parse(value);
        return data;
    }
}

2.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{           
    services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        var dateConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter
        {
            DateTimeFormat = "dd'-'MM'-'yyyy'T'HH':'mm"
        };

        options.SerializerSettings.Converters.Add(dateConverter);
        options.SerializerSettings.Culture = new CultureInfo("en-IE");
        options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
    });
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });      

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();                
    });

}

结果:

enter image description here
如果您在项目中使用本地化,请配置如 this然后像下面这样改变:

1.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddControllers().AddViewLocalization(
    LanguageViewLocationExpanderFormat.Suffix,
    opts => { opts.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization()
    .AddNewtonsoftJson(options =>
    {
        var dateConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter
        {
            DateTimeFormat = "dd'-'MM'-'yyyy'T'HH':'mm"
        };

        options.SerializerSettings.Converters.Add(dateConverter);
        options.SerializerSettings.Culture = new CultureInfo("en-IE");
        options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
    }); 

    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new CultureInfo[] {
            new CultureInfo("en"),
            new CultureInfo("de"),
            new CultureInfo("en-IE")
    };
        options.DefaultRequestCulture = new RequestCulture("en");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;

        options.RequestCultureProviders = new[]{ new CustomRouteDataRequestCultureProvider{
            IndexOfCulture=1,
        }};
    });

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
    var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(options.Value);

    app.UseHttpsRedirection();


    app.UseRouting();

    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapControllerRoute("LocalizedDefault", "{culture:cultrue}/{controller=Home}/{action=Index}/{id?}");

    });

}

2. Controller :
[Route("{culture?}/api/[controller]")]
//[Route("api/[controller]")]
public class ValuesController : Controller
{}

结果:

enter image description here

关于c# - Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578862/

相关文章:

azure - 通过 Web API 而不是 Graph API 重置 Azure AD 密码

asp.net-core - 访问在我的 quartz 作业上使用 DbContext 的服务时出错

c# - 在导航属性上使用 EF Core HasQueryFilter

c# - Parallel.ForEach 是否使用 ASP.NET 线程池中的线程?

c# - 用于身份验证的自定义 url

c# - Tablets.Count 方法中的 ArgumentException

c# - ASP.NET Core 应用程序日志未写入 Azure 应用服务中的 Blob

c# - .NET Core 128kb 部署到 Azure 应用服务的文件大小限制

c# - 订阅其他项目中的 Controller 引发的事件

c# - 临时存储特定用户的对话