欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何在?ASP.NET?Core?Web?API?中處理?Patch?請求

 更新時(shí)間:2023年05月14日 15:47:11   作者:alby  
這篇文章主要介紹了在?ASP.NET?Core?Web?API中處理Patch請求,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、概述

PUT 和 PATCH 方法用于更新現(xiàn)有資源。 它們之間的區(qū)別是,PUT 會(huì)替換整個(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 = "姓名", // 可能會(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 而沒有其他參數(shù),從 HttpContext.Request.Form.Keys 可以得知這一點(diǎn)。如果不使用 AutoMapper,那么接下來是丑陋的判斷:

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!;
}
// ...

本文提供一種方式來簡化這個(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。

五、定義 AutoMapper 的 TypeConverter

public 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;
    }
}

上述代碼可用其他手段來代替反射。

六、模型映射

[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 =>
    {
        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 = "如果客戶端沒有提供本參數(shù),那我的值不會(huì)被改變"
    };
    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'

源碼

Tubumu.PatchMapper

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

參考資料

GraphQL.NET

如何在 ASP.NET Core Web API 中處理 JSON Patch 請求

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

相關(guān)文章

  • 聊一聊Asp.net過濾器Filter那一些事

    聊一聊Asp.net過濾器Filter那一些事

    這篇文章主要介紹了聊一聊Asp.net過濾器Filter那一些事,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • ASP.Net中利用CSS實(shí)現(xiàn)多界面的兩種方法

    ASP.Net中利用CSS實(shí)現(xiàn)多界面的兩種方法

    這篇文章主要介紹了ASP.Net中利用CSS實(shí)現(xiàn)多界面的兩種方法,包括動(dòng)態(tài)加載css樣式與動(dòng)態(tài)設(shè)置頁面同類控件的方法來實(shí)現(xiàn)該功能,是非常具有實(shí)用價(jià)值的技巧,需要的朋友可以參考下
    2014-12-12
  • .net indexOf(String.indexOf 方法)

    .net indexOf(String.indexOf 方法)

    字符串的IndexOf()方法搜索在該字符串上是否出現(xiàn)了作為參數(shù)傳遞的字符串,如果找到字符串,則返回字符的起始位置 (0表示第一個(gè)字符,1表示第二個(gè)字符依此類推)如果說沒有找到則返回 -1
    2012-10-10
  • .Net?ORM?訪問?Firebird?數(shù)據(jù)庫的方法

    .Net?ORM?訪問?Firebird?數(shù)據(jù)庫的方法

    這篇文章簡單介紹了在?.net6.0?環(huán)境中使用?FreeSql?對?Firebird?數(shù)據(jù)庫的訪問,目前?FreeSql?還支持.net?framework?4.0?和?xamarin?平臺(tái)上使用,對.Net?ORM?訪問?Firebird?數(shù)據(jù)庫相關(guān)知識感興趣的朋友一起看看吧
    2022-07-07
  • asp.net操作過程中常見錯(cuò)誤的解決方法

    asp.net操作過程中常見錯(cuò)誤的解決方法

    這篇文章主要介紹了asp.net操作過程中常見錯(cuò)誤的解決方法,主要有IIS無法識別ASP.NET、 SQL Server不允許進(jìn)行遠(yuǎn)程連接可能會(huì)導(dǎo)致此失敗等問題,感興趣的小伙伴們可以參考一下
    2015-10-10
  • C#實(shí)現(xiàn)上傳照片到物理路徑,并且將地址保存到數(shù)據(jù)庫的小例子

    C#實(shí)現(xiàn)上傳照片到物理路徑,并且將地址保存到數(shù)據(jù)庫的小例子

    這篇文章主要介紹了c#上傳圖片,并將地址保存到數(shù)據(jù)庫中的簡單實(shí)例,有需要的朋友可以參考一下
    2013-12-12
  • MVC4制作網(wǎng)站教程第四章 前臺(tái)欄目瀏覽4.5

    MVC4制作網(wǎng)站教程第四章 前臺(tái)欄目瀏覽4.5

    這篇文章主要為大家詳細(xì)介紹了MVC4制作網(wǎng)站教程,前臺(tái)欄目瀏覽功能實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-08-08
  • .NET Core3.0 日志 logging的實(shí)現(xiàn)

    .NET Core3.0 日志 logging的實(shí)現(xiàn)

    這篇文章主要介紹了.NET Core3.0 日志 logging的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • ASP.NET下使用WScript.Shell執(zhí)行命令

    ASP.NET下使用WScript.Shell執(zhí)行命令

    ASP.NET下有自己的執(zhí)行CMD命令的方式,這里用WScript.Shell似有畫蛇添足之嫌,但是我們也不能排除真的有機(jī)器禁用了.NET的相關(guān)類,未雨綢繆嘛。當(dāng)然也不僅僅局限于WScript.Shell,只要是ASP中能用的組件,統(tǒng)統(tǒng)都可以用于ASP.NET中,而且還更方便!
    2008-05-05
  • Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟

    Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟

    這篇文章主要介紹了Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟,幫助大家更好的理解和學(xué)習(xí)使用Asp.Net Core,感興趣的朋友可以了解下
    2021-03-03

最新評論