IParsable 是 .Net 7 中新增的接口,它可以將字符串轉換為對應的實體。在 Controller 的 Route 綁定中可以使用 IParsable 來綁定復雜的實體。
實驗背景
假設有一個需要將 route "report/{month}-{day}" 綁定到 MyDate 對象上的場景。
在 .Net 7 之前,通常是使用兩個參數來接收綁定的 month 和 day,然后在代碼中實例化 MyDate 對象。例如:
[Route("report/{month}-{day}")]
public?ActionResult?GetReport(int?month,?int?day)
{var?myDate?=?new?MyDate?{?Month?=?month,?Day?=?day?};//?使用?myDate
}
使用 IParsable
在 .Net 7 中,可以直接讓 MyDate 實現 IParsable 接口,然后在 route 中綁定 "report/{myDate}"。這樣 MyDate 就能直接從 route 上綁定,省去了手動實例化的步驟。
下面是一個示例代碼:
public?class?MyDate?:?IParsable<MyDate>
{public?int?Month?{?get;?set;?}public?int?Day?{?get;?set;?}public?void?Parse(string?input){var?parts?=?input.Split('-');Month?=?int.Parse(parts[0]);Day?=?int.Parse(parts[1]);}public?static?MyDate?Parse(string?s,?IFormatProvider??provider){var?date?=?new?MyDate();date.Parse(s);return?date;}public?static?bool?TryParse(string??s,?IFormatProvider??provider,?out?MyDate?result){try{result?=?Parse(s,?provider);return?true;}catch{result?=?default;return?false;}}
}[HttpGet("report/{myDate}")]
public?ActionResult?GetReport(MyDate?myDate)
{//?myDate?已經被正確地綁定
}
參考資料
IParsable[1]
5 new MVC features in .NET 7[2]
本文采用 Chat OpenAI 輔助注水澆筑而成,如有雷同,完全有可能。
本文作者:newbe36524
本文鏈接:https://www.newbe.pro/ChatAI/How-to-use-IParsable-in-route-binding/
版權聲明:本博客所有文章除特別聲明外,均采用 BY-NC-SA 許可協議。轉載請注明出處!
參考資料
[1]
IParsable: https://learn.microsoft.com/en-us/dotnet/api/system.iparsable-1?view=net-7.0&WT.mc_id=DX-MVP-5003606
[2]5 new MVC features in .NET 7: https://andrewlock.net/5-new-mvc-features-in-dotnet-7/