一、概述
PUT
和PATCH
方法用于更新現(xiàn)有資源。 它們之間的區(qū)別是,PUT 會替換整個(gè)資源,而 PATCH 僅指定更改。
在 ASP.NET Core Web API 中,由于 C# 是一種靜態(tài)語言(dynamic
在此不表),當(dāng)我們定義了一個(gè)類型用于接收 HTTP Patch 請求參數(shù)的時(shí)候,在 Action
中無法直接從實(shí)例中得知客戶端提供了哪些參數(shù)。
比如定義一個(gè)輸入模型和數(shù)據(jù)庫實(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)
{
// 測試代碼暫時(shí)將 AutoMapper 配置放在方法內(nèi)。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PersonInput, PersonEntity>());
});
var mapper = config.CreateMapper();
// entity 從數(shù)據(jù)庫讀取,這里僅演示。
var entity = new PersonEntity
{
Name = "姓名", // 可能會被改變
Age = 18, // 可能會被改變
Gender = "我可能會被改變",
};
// 如果客戶端只輸入 Name 字段,entity 的 Age 和 Gender 將不能被正確映射或被置為 null。
mapper.Map(input, entity);
return Ok();
}
curl --location --request PATCH 'http://localhost:5094/test/patch' \
--form 'Name="foo"'
如果客戶端只提供了 Name
而沒有其他參數(shù),從 HttpContext.Request.Form.Keys
可以得知這一點(diǎn)。如果不使用 AutoMapper,那么就需要使用丑陋的判斷:
[HttpPatch]
[Route("patch")]
public ActionResult Patch([FromForm] PersonInput input)
{
var keys = _httpContextAccessor.HttpContext.Request.Form.Keys.Select(m => m.ToLower());
var entity = new PersonEntity
{
Name = "姓名", // 可能會被改變
Age = 18, // 可能會被改變
Gender = "我可能會被改變",
};
if (keys.Contains("name"))
{
// 更新 Name(這里忽略合法性判斷)
entity.Name = input.Name!;
}
if (keys.Contains("age"))
{
// 更新 Age(這里忽略合法性判斷)
entity.Age = input.Age!.Value;
}
// ... 其他判斷
return Ok();
}
本文提供一種方式來簡化這個(gè)步驟。
二、將 Keys 保存在 Input Model 中
定義一個(gè)名為 PatchInput
的類:
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 和 ModelBinder
public 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 類
if (typeof(PatchInput).IsAssignableFrom(context.Metadata.ModelType)
&& modelBinder.GetType().ToString().EndsWith("ComplexObjectModelBinder"))
{
modelBinder = new PatchModelBinder(modelBinder);
}
return modelBinder;
}
}
四、在 ASP.NET Core 項(xiàng)目中替換 ModelBinderFactory
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddPatchMapper();
AddPatchMapper
是一個(gè)簡單的擴(kuò)展方法:
public static class PatchMapperExtensions
{
public static IServiceCollection AddPatchMapper(this IServiceCollection services)
{
services.Replace(ServiceDescriptor.Singleton<IModelBinderFactory, PatchModelBinderFactory>());
return services;
}
}
到目前為止,在 Action 中已經(jīng)能獲取到請求的 Key 了。
[HttpPatch]
[Route("patch")]
public ActionResult Patch([FromForm] PersonInput input)
{
// 不需要手工給 input.PatchKeys 賦值。
return Ok();
}
PatchKeys
的作用是利用 AutoMapper。
五、擴(kuò)展 AutoMapper
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination> CreateMapWithPath<TSource, TDestination>(this IMapperConfigurationExpression cfg)
where TSource : PatchInput
{
return cfg.CreateMap<TSource, TDestination>().ApplyPatchKeysCondition<TSource, TDestination>();
}
private static IMappingExpression<TSource, TDestination> ApplyPatchKeysCondition<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> mappingExpression)
where TSource : PatchInput
{
mappingExpression.ForAllMembers(opts =>
{
opts.Condition((src, dest, srcMember, destMember, context) =>
{
return src.PatchKeys == null || src.PatchKeys.Contains(opts.DestinationMember.Name.ToLower());
});
});
return mappingExpression;
}
}
六、模型映射
[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 以便于未來支持更多的輸入格式。
// 3. 目前還沒有支持多級結(jié)構(gòu)。
// 4. 測試代碼暫時(shí)將 AutoMapper 配置放在方法內(nèi)。
var config = new MapperConfiguration(cfg =>
{
// 使用 CreateMapWithPath 代替 CreateMap
cfg.CreateMapWithPath<PersonInput, PersonEntity>();
});
var mapper = config.CreateMapper();
// PersonEntity 有 3 個(gè)屬性,客戶端如果提供的參數(shù)參數(shù)不足 3 個(gè),在 Map 時(shí)未提供參數(shù)的屬性值不會被改變。
var entity = new PersonEntity
{
Name = "姓名",
Age = 18,
Gender = "如果客戶端沒有提供本參數(shù),那我的值不會被改變"
};
mapper.Map(input, entity);
return Ok();
}
七、測試
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'
下一步
嘗試 INotifypropertyChanged
和 Fody
的 PropertyChanged
來獲取 Keys。
源碼
Tubumu.PatchMapper文章來源:http://www.zghlxwxcb.cn/news/detail-442476.html
參考資料
GraphQL.NET
如何在 ASP.NET Core Web API 中處理 JSON Patch 請求文章來源地址http://www.zghlxwxcb.cn/news/detail-442476.html
到了這里,關(guān)于在 ASP.NET Core Web API 中處理 Patch 請求的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!