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

Swagger .netcore 3.1 in Web Api, set the date time format with swagger UI(Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式)

本文介绍了Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

2020-03-07T14:49:48.549Z

07-03-2020T14:49

我正在尝试删除秒并将日期格式放入dd/MM/yyyy HH:mm",现在我已经尝试过

 services.AddControllers().AddNewtonsoftJson(选项 =>{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.控制器:

[Route("api/[controller]")]公共类 ValuesController : 控制器{[HttpGet]公共日期时间获取(){var 数据 = 日期时间.现在;返回数据;}//POST api/<控制器>[HttpPost]公共日期时间发布([FromBody]字符串值){var data = DateTime.Parse(value);返回数据;}}

2.Startup.cs:

public void ConfigureServices(IServiceCollection services){服务.AddControllers().AddNewtonsoftJson(选项 =>{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 = "TXkgQVBJ", Version = "v1" });});}//这个方法被运行时调用.使用此方法配置 HTTP 请求管道.公共无效配置(IApplicationBuilder 应用程序,IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseSwagger();app.UseSwaggerUI(c =>{c.SwaggerEndpoint("/swagger/v1/swagger.json", "我的 API V1");});app.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(端点 =>{端点.MapControllers();});}

结果:

如果您在项目中使用本地化,请像

I am wondering if anyone can help me, I am trying to change the date format in swagger UI from

2020-03-07T14:49:48.549Z

to

07-03-2020T14:49

I am trying to remove the seconds and put the date format into "dd/MM/yyyy HH:mm", now I have tried

    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;
        })

I seen various example on the web and none of which seems to work.

解决方案

Here is a working demo like below:

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 = "TXkgQVBJ", 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();                
    });

}

Result:

If you use localization in your project,please configure like this and then change like below:

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 = "TXkgQVBJ", 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
{}

Result:

这篇关于Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式