第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

ASP .Net Core空數(shù)組查詢參數(shù)綁定異常

ASP .Net Core空數(shù)組查詢參數(shù)綁定異常

C#
梵蒂岡之花 2022-12-31 13:34:49
我有一個(gè)如下所示的 WebAPI 控制器:[Route("api/[controller]")][ApiController]public class ValuesController : ControllerBase{    [HttpGet]    public ActionResult<string> Get([FromQuery]DataFilter dataFilter)    {        return string.Join(Environment.NewLine, dataFilter?.Filter?.Select(f => f.ToString()) ?? Enumerable.Empty<string>());    }}沒什么特別的,只是一個(gè)控制器,它從查詢字符串中接收一些數(shù)據(jù)并將其作為響應(yīng)輸出。它收到的類如下所示:public class DataFilter{    public IEnumerable<FilterType> Filter { get; set; }}public enum FilterType{    One,    Two,    Three,}這些只是用于說明問題的示例類,當(dāng)嘗試像這樣調(diào)用此方法時(shí),這是一個(gè)驗(yàn)證錯(cuò)誤:/api/values?filter=和回應(yīng):{  "errors": {    "Filter": [      "The value '' is invalid."    ]  },  "title": "One or more validation errors occurred.",  "status": 400,  "traceId": "80000164-0002-fa00-b63f-84710c7967bb"}如果我將我的 FilterType 設(shè)置為可為空,它會(huì)起作用,但在這種情況下,數(shù)組只包含空值。如果這樣使用:/api/values?filter=&filter=&filter=它將只包含 3 個(gè)空值。我希望它只是空的或 null,因?yàn)闆]有傳遞任何實(shí)際值。ASP .Net Core github 帳戶包含一些類似的問題,但據(jù)報(bào)道它們已在我正在使用的 2.2 中修復(fù)。但也許它們是不同的,或者我誤解了一些東西。EDIT_0:只是為了說明我對(duì)可空性的意思。如果我將課程更改為:public IEnumerable<FilterType?> Filter { get; set; } //notice that nullable is added to an Enum, not the list然后當(dāng)這樣調(diào)用時(shí):/api/values?filter=&filter=&filter=我的“過濾器”屬性中有 3 個(gè)元素。所有空值。不完全是我所期望的。作為解決方法很好,但根本不是解決方案。
查看完整描述

3 回答

?
哆啦的時(shí)光機(jī)

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊

您可以創(chuàng)建自定義模型綁定器,其任務(wù)是刪除默認(rèn)生成的驗(yàn)證錯(cuò)誤CollectionModelBinder。這在您的情況下應(yīng)該足夠了,因?yàn)槟J(rèn)模型活頁夾按您需要的方式工作,不會(huì)向集合中添加無效值。


public class EmptyCollectionModelBinder : CollectionModelBinder<FilterType>

{

    public EmptyCollectionModelBinder(IModelBinder elementBinder) : base(elementBinder)

    {

    }


    public override async Task BindModelAsync(ModelBindingContext bindingContext)

    {

        await base.BindModelAsync(bindingContext);

        //removing validation only for this collection

        bindingContext.ModelState.ClearValidationState(bindingContext.ModelName);

    }

}

創(chuàng)建并注冊(cè)模型活頁夾提供程序


public class EmptyCollectionModelBinderProvider : IModelBinderProvider

{

    public IModelBinder GetBinder(ModelBinderProviderContext context)

    {

        if (context == null)

        {

            throw new ArgumentNullException(nameof(context));

        }


        if (context.Metadata.ModelType == typeof(IEnumerable<FilterType>))

        {

            var elementBinder = context.CreateBinder(context.MetadataProvider.GetMetadataForType(typeof(FilterType)));


            return new EmptyCollectionModelBinder(elementBinder);

        }


        return null;

    }

}

啟動(dòng).cs


services

    .AddMvc(options =>

    {

        options.ModelBinderProviders.Insert(0, new EmptyCollectionModelBinderProvider());

    })


查看完整回答
反對(duì) 回復(fù) 2022-12-31
?
ITMISS

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊

你有幾個(gè)選擇。您可以創(chuàng)建一個(gè)自定義模型活頁夾來處理您的過濾器類型或者:

您可以使用 Nullables 創(chuàng)建 IEnumerable:

public IEnumerable<FilterType?> Filter { get; set; }

并過濾掉調(diào)用代碼中的空值:

return string.Join(Environment.NewLine, dataFilter?.Filter?.Where(f => f != null)
   .Select(f => f.ToString()) ?? Enumerable.Empty<string>());


查看完整回答
反對(duì) 回復(fù) 2022-12-31
?
交互式愛情

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊

我已經(jīng)使用自定義 TypeConverter 解決了這個(gè)問題,并轉(zhuǎn)移到 JSON 格式來傳遞數(shù)組(例如 filter=["one","two"])


這是我定義它的方式:


public class JsonArrayTypeConverter<T> : TypeConverter

{

    private static readonly TypeConverter _Converter = TypeDescriptor.GetConverter(typeof(T));


    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) =>

        sourceType == typeof(string) || TypeDescriptor.GetConverter(sourceType).CanConvertFrom(context, sourceType);


    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)

    {

        try

        {

            return JsonConvert.DeserializeObject<IEnumerable<T>>((string)value);

        }

        catch (Exception)

        {

            var dst = _Converter.ConvertFrom(context, culture, value); //in case this is not an array or something is broken, pass this element to a another converter and still return it as a list

            return new T[] { (T)dst };

        }

    }

}

和全球注冊(cè):


TypeDescriptor.AddAttributes(typeof(IEnumerable<FilterType>), new TypeConverterAttribute(typeof(JsonArrayTypeConverter<FilterType>)));

現(xiàn)在我的過濾器列表中沒有空項(xiàng)目,并且還支持具有多種類型支持(枚舉、字符串、整數(shù)等)的 JSON 列表。


唯一的缺點(diǎn)是這不能像以前那樣處理傳遞的元素(例如 filter=one&filter=two&filter=three)。瀏覽器地址欄中的查詢字符串也不好看。


查看完整回答
反對(duì) 回復(fù) 2022-12-31
  • 3 回答
  • 0 關(guān)注
  • 155 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)