.NET Core 2.2 新增部分功能使用嘗鮮


前言

    美國當地時間12月4日,微軟2019開發者大會中發布了一系列的重磅消息,包含了軟硬件和開源社區的各種好消息是鋪天蓋地,作為一名普通的開發者,我第一時間下載了 .NET Core 2.2 的源碼,針對發布說明逐條瀏覽,並截取了部分常用的功能進行嘗試,下面就與大家分享。

1. 對 API 接口統一大小寫的支持
  • 1.1 查看以下接口代碼
       [HttpGet]
        public ActionResult<UserInfo> Get()
        {
            return new UserInfo() { Name = "Ron.liang", RegTime = DateTime.Now };
        }

        [HttpGet("{id}")]
        public ActionResult<Dictionary<string, string>> Get(int id)
        {
            return new Dictionary<string, string> {
                { "Name", "Ron.liang" },
                { "RegTime", DateTime.Now.ToString() }
            };
        }

        // 接口 1 輸出
        {
            name: "Ron.liang",
            regTime: "2018-12-05T10:40:37.5090634+08:00"
        }
        // 接口 2 輸出
        {
            Name: "Ron.liang",
            RegTime: "2018-12-05T10:40:58.5072645+08:00"
        }
  • 1.2 默認情況下,字典內地字段名稱將不會被應用 CamelCaseNamingStrategy ,所以如果要保持字段名稱大小寫統一的問題,可在 ConfigureServices 中加入 AddJsonOptions(o => o.UseCamelCasing(true))
   public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddJsonOptions(o => o.UseCamelCasing(false)).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
  • AddJsonOptions 內置兩個默認擴展,你可以使用 UseCamelCasing 或者 UseMemberCasing ,如果使用 UseMemberCasing ,表示使用成員字段的大小寫規則,即不改變大小寫輸出

  • 1.3 有意思的是,AddJsonOptions(o => o.UseCamelCasing(true)) 顯式傳入值的方式是由 JamesNK 這個哥們杠出來的結果,詳見

https://github.com/aspnet/Mvc/pull/7962
2. 復合驗證-驗證模型的擴展
  • 1.1 在之前的版本中,如果希望對一個屬性應用多個驗證,必須書寫多個驗證類,如
    public class UserInfo
    {
        [StringLength(20), RegularExpression(@"^[a-zA-Z]$")]
        public string Name { get; set; }
        [StringLength(20), RegularExpression(@"^[a-zA-Z]$")]
        public string Title { get; set; }
        public DateTime RegTime { get; set; }
    }
  • 2.2 在 .NET Core 2.2 以后的版本中,你可以通過擴展來避免這個問題,通過繼承自 ValidationProviderAttribute 並重寫 GetValidationAttributes 方法來實現復合驗證
    public class UserInfo
    {
        [Name]
        public string Name { get; set; }
        [Name]
        public string Title { get; set; }
        public DateTime RegTime { get; set; }
    }

    public class NameAttribute : ValidationProviderAttribute
    {
        public override IEnumerable<ValidationAttribute> GetValidationAttributes()
        {
            return new List<ValidationAttribute>
            {
                new RequiredAttribute(),
                new RegularExpressionAttribute(pattern: "[A-Za-z]*"),
                new StringLengthAttribute(maximumLength: 20)
            };
        }
    }
  • 2.3 看起來是不是簡潔多了
3. API Controller 增加默認的響應處理類型
  • 3.1 在以前的版本中,可以通過在 API 上增加特性 ProducesResponseType 來處理不同的 HttpCode 響應,然后 pranavkm 覺得,我們應該像 Swagger/OpenApi 一樣,增加一個默認的響應處理類型,然后就出現了
namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// A filter that specifies the type of the value and status code returned by the action.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class ProducesResponseTypeAttribute : Attribute, IApiResponseMetadataProvider
    {
        ....

    }
  • 3.2 說實話,上面的這個類,我沒搞懂到底怎么用,有知道的朋友請在評論中回復,我將把它加入文中,感謝。(經 牛排大叔. 解釋,ProducesResponseTypeAttribute應該是給swagger顯示API返回描述配套用的。 感謝!

4. Razor 視圖部分優化

  • 4.1 .NET Core 團隊認為,在 Razor 視圖中,如果使用 @Html.Parital 引入分部視圖,可能存在潛在的死鎖情況,所以將 @Html.Parital 變更為
 //舊的:
 @Html.Partial("_StatusMessage", Model.StatusMessage)

 // 新的:
 <partial name="_StatusMessage", for="StatusMessage" />
  • 4.2 如果你現在嘗試使用 .NET Core 2.2 創建新的 MVC 項目,你就馬上可以看到該變化了
5. 鈎子
  • 5.1 通過設置環境變量,可以在程序 Main 方法運行前執行一些業務邏輯,但是 .NET Core 團隊建議,該功能只是一些低級的鈎子,不要用於復雜的業務,如有需要,還是應該使用依賴注入,有空再嘗試一下該功能,應該會很有意思

結語

  • 在 .NET Core 2.2 版本中,有很多性能上的優化,可以看到開源社區的力量確實強大,本文僅節選了部分常用功能進行嘗試,相信后續會有更多朋友的分享
  • 期待 3.0 早日到來


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM