国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

如何在?ASP.NET?Core?Web?API?中處理?Patch?請(qǐng)求

瀏覽:2日期:2022-06-14 15:06:01
目錄一、概述二、將 Keys 保存在 Input Model 中三、定義 ModelBinderFactory 和 ModelBinder四、在 ASP.NET Core 項(xiàng)目中替換 ModelBinderFactory五、定義 AutoMapper 的 TypeConverter六、模型映射七、測(cè)試源碼參考資料一、概述

PUT 和 PATCH 方法用于更新現(xiàn)有資源。 它們之間的區(qū)別是,PUT 會(huì)替換整個(gè)資源,而 PATCH 僅指定更改。

在 ASP.NET Core Web API 中,由于 C# 是一種靜態(tài)語(yǔ)言(dynamic 在此不表),當(dāng)我們定義了一個(gè)類(lèi)型用于接收 HTTP Patch 請(qǐng)求參數(shù)的時(shí)候,在 Action 中無(wú)法直接從實(shí)例中得知客戶端提供了哪些參數(shù)。

比如定義一個(gè)輸入模型和數(shù)據(jù)庫(kù)實(shí)體:

public class PersonInput{ public string? Name { get; set; } public int? Age { get; set; } public string? Gender { get; set; }}public class PersonEntity{ public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; }}

再定義一個(gè)以 FromForm 形式接收參數(shù)的 Action:

[HttpPatch][Route('patch')]public ActionResult Patch([FromForm] PersonInput input){ // 測(cè)試代碼暫時(shí)將 AutoMapper 配置放在方法內(nèi)。 var config = new MapperConfiguration(cfg => {cfg.CreateMap<PersonInput, PersonEntity>()); }); var mapper = config.CreateMapper(); // entity 從數(shù)據(jù)庫(kù)讀取,這里僅演示。 var entity = new PersonEntity {Name = '姓名', // 可能會(huì)被改變Age = 18, // 可能會(huì)被改變Gender = '我可能會(huì)被改變', }; // 如果客戶端只輸入 Name 字段,entity 的 Age 和 Gender 將不能被正確映射或被置為 null。 mapper.Map(input, entity); return Ok();}curl --location --request PATCH 'http://localhost:5094/test/patch' \--form 'Name='foo''

如果客戶端只提供了 Name 而沒(méi)有其他參數(shù),從 HttpContext.Request.Form.Keys 可以得知這一點(diǎn)。如果不使用 AutoMapper,那么接下來(lái)是丑陋的判斷:

var keys = _httpContextAccessor.HttpContext.Request.Form.Keys;if(keys.Contains('Name')){ // 更新 Name(這里忽略合法性判斷) entity.Name = input.Name!;}if (keys.Contains('Age')){ // 更新 Age(這里忽略合法性判斷) entity.Age = input.Age!;}// ...

本文提供一種方式來(lái)簡(jiǎn)化這個(gè)步驟。

二、將 Keys 保存在 Input Model 中

定義一個(gè)名為 PatchInput 的類(lèi):

public abstract class PatchInput{ [BindNever] public ICollection<string>? PatchKeys { get; set; }}

PatchKeys 屬性不由客戶端提供,不參與默認(rèn)綁定。

PersonInput 繼承自 PatchInput:

public class PersonInput : PatchInput{ public string? Name { get; set; } public int? Age { get; set; } public string? Gender { get; set; }}三、定義 ModelBinderFactory 和 ModelBinderpublic class PatchModelBinder : IModelBinder{ private readonly IModelBinder _internalModelBinder; public PatchModelBinder(IModelBinder internalModelBinder) {_internalModelBinder = internalModelBinder; } public async Task BindModelAsync(ModelBindingContext bindingContext) {await _internalModelBinder.BindModelAsync(bindingContext);if (bindingContext.Model is PatchInput model){ // 將 Form 中的 Keys 保存在 PatchKeys 中 model.PatchKeys = bindingContext.HttpContext.Request.Form.Keys;} }}public class PatchModelBinderFactory : IModelBinderFactory{ private ModelBinderFactory _modelBinderFactory; public PatchModelBinderFactory(IModelMetadataProvider metadataProvider,IOptions<MvcOptions> options,IServiceProvider serviceProvider) {_modelBinderFactory = new ModelBinderFactory(metadataProvider, options, serviceProvider); } public IModelBinder CreateBinder(ModelBinderFactoryContext context) {var modelBinder = _modelBinderFactory.CreateBinder(context);// ComplexObjectModelBinder 是 internal 類(lèi)if (typeof(PatchInput).IsAssignableFrom(context.Metadata.ModelType) && modelBinder.GetType().ToString().EndsWith('ComplexObjectModelBinder')){ modelBinder = new PatchModelBinder(modelBinder);}return modelBinder; }}四、在 ASP.NET Core 項(xiàng)目中替換 ModelBinderFactoryvar builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddPatchMapper();

AddPatchMapper 是一個(gè)簡(jiǎn)單的擴(kuò)展方法:

public static class PatchMapperExtensions{ public static IServiceCollection AddPatchMapper(this IServiceCollection services) {services.Replace(ServiceDescriptor.Singleton<IModelBinderFactory, PatchModelBinderFactory>());return services; }}

到目前為止,在 Action 中已經(jīng)能獲取到請(qǐng)求的 Key 了。

[HttpPatch][Route('patch')]public ActionResult Patch([FromForm] PersonInput input){ // 不需要手工給 input.PatchKeys 賦值。 return Ok();}

PatchKeys 的作用是利用 AutoMapper。

五、定義 AutoMapper 的 TypeConverterpublic class PatchConverter<T> : ITypeConverter<PatchInput, T> where T : new(){ /// <inheritdoc /> public T Convert(PatchInput source, T destination, ResolutionContext context) {destination ??= new T();var sourceType = source.GetType();var destinationType = typeof(T);foreach (var key in source.PatchKeys ?? Enumerable.Empty<string>()){ var sourcePropertyInfo = sourceType.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (sourcePropertyInfo != null) {var destinationPropertyInfo = destinationType.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);if (destinationPropertyInfo != null){ var sourceValue = sourcePropertyInfo.GetValue(source); destinationPropertyInfo.SetValue(destination, sourceValue);} }}return destination; }}

上述代碼可用其他手段來(lái)代替反射。

六、模型映射[HttpPatch][Route('patch')]public ActionResult Patch([FromForm] PersonInput input){ // 1. 目前僅支持 `FromForm`,即 `x-www-form_urlencoded` 和 `form-data`;暫不支持 `FromBody` 如 `raw` 等。 // 2. 使用 ModelBinderFractory 創(chuàng)建 ModelBinder 而不是 ModelBinderProvider 以便于未來(lái)支持更多的輸入格式。 // 3. 目前還沒(méi)有支持多級(jí)結(jié)構(gòu)。 // 4. 測(cè)試代碼暫時(shí)將 AutoMapper 配置放在方法內(nèi)。 var config = new MapperConfiguration(cfg => {cfg.CreateMap<PersonInput, PersonEntity>().ConvertUsing(new PatchConverter<PersonEntity>()); }); var mapper = config.CreateMapper(); // PersonEntity 有 3 個(gè)屬性,客戶端如果提供的參數(shù)參數(shù)不足 3 個(gè),在 Map 時(shí)未提供參數(shù)的屬性值不會(huì)被改變。 var entity = new PersonEntity {Name = '姓名',Age = 18,Gender = '如果客戶端沒(méi)有提供本參數(shù),那我的值不會(huì)被改變' }; mapper.Map(input, entity); return Ok();}七、測(cè)試curl --location --request PATCH 'http://localhost:5094/test/patch' \--form 'Name='foo''

curl --location --request PATCH 'http://localhost:5094/test/patch' \--header 'Content-Type: application/x-www-form-urlencoded' \--data-urlencode 'Name=foo'源碼

Tubumu.PatchMapper

支持 FromForm,即 x-www-form_urlencoded 和 form-data。支持 FromBody 如 raw 等。支持多級(jí)結(jié)構(gòu)。參考資料

GraphQL.NET

如何在 ASP.NET Core Web API 中處理 JSON Patch 請(qǐng)求

到此這篇關(guān)于在 ASP.NET Core Web API 中處理 Patch 請(qǐng)求的文章就介紹到這了,更多相關(guān)ASP.NET Core Web API 處理 Patch 請(qǐng)求內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: ASP.NET
主站蜘蛛池模板: 四子王旗| 浮梁县| 上杭县| 莆田市| 开平市| 通州区| 区。| 九龙县| 手机| 固原市| 丰顺县| 库伦旗| 民权县| 奉贤区| 海口市| 呼图壁县| 共和县| 济南市| 蓝山县| 兴海县| 福鼎市| 东明县| 德庆县| 德格县| 西峡县| 凭祥市| 灵璧县| 成武县| 宁海县| 肥东县| 中西区| 东至县| 德惠市| 荣昌县| 邢台市| 九江县| 深圳市| 若羌县| 福建省| 定陶县| 德清县|