.Net Core解決WebAPI中返回時(shí)間格式帶T的問題
在項(xiàng)目開發(fā)中遇到了返回的時(shí)間格式帶T的問題,如圖所示:

直接把這種結(jié)果返回給前端,前端很難處理這個(gè)時(shí)間格式問題,所以就需要后端在返回?cái)?shù)據(jù)的時(shí)候?qū)@種格式進(jìn)行處理。
新建Order類:
using System;
namespace WebApiTest
{
public class Order
{
public int ID { get; set; }
public DateTime OrderTime { get; set; }
}
}新建一個(gè)格式化類DatetimeJsonConverter,繼承自JsonConverter,然后重寫里面的方法:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace WebApiTest
{
/// <summary>
/// 格式化返回的時(shí)間格式
/// </summary>
public class DatetimeJsonConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
if (DateTime.TryParse(reader.GetString(), out DateTime date))
return date;
}
return reader.GetDateTime();
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
}然后修改Startup類的ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
#region 解決返回時(shí)間帶T的問題
services.AddControllers().AddJsonOptions(configure =>
{
configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
});
#endregion
}返回結(jié)果

到此這篇關(guān)于.Net Core解決WebAPI中返回時(shí)間格式帶T的問題的文章就介紹到這了,更多相關(guān).Net Core返回時(shí)間格式帶T內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Repeater控件分別綁定數(shù)組和ArrayList實(shí)現(xiàn)思路
在后臺(tái)用DataSource綁上數(shù)據(jù)源(數(shù)組或ArrayList)在調(diào)用DataBind()方法,在前臺(tái)調(diào)用%# GetDataItem()%,感興趣的朋友可以了解下啊,望本文可以鞏固你的數(shù)據(jù)綁定知識(shí)2013-01-01
.net webapi接收xml格式數(shù)據(jù)的3種情況小結(jié)
這篇文章主要給大家總結(jié)介紹了關(guān)于.net webapi接收xml格式數(shù)據(jù)的3種情況,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02
.NET?core項(xiàng)目AsyncLocal在鏈路追蹤中的應(yīng)用
這篇文章主要為大家介紹了.NET?core項(xiàng)目zhong?AsyncLocal在鏈路追蹤中的應(yīng)用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
asp.net微信開發(fā)(已關(guān)注用戶管理)
這篇文章主要介紹了asp.net微信開發(fā)中有關(guān)已關(guān)注用戶管理的相關(guān)內(nèi)容,需要的朋友可以參考下2015-11-11
asp.net checkbox 動(dòng)態(tài)綁定id GridView刪除提示
asp.net checkbox 動(dòng)態(tài)綁定id,需要的朋友可以參考下。雖然簡單但不知道挺麻煩的。GridView刪除提示2009-10-10

