我有一個 ASP.NET Core Web API 端點,它采用 (FromBody) 下面定義的 Search 物件
public class Search {
public int PageSize {get;set;}
public Expression Query{get;set;}
}
Public class Expression {
public string Type {get;set;}
}
public class AndExpression {
public IList<Expression> Expressions {get;set;}
}
public class MatchesExpression {
public string FieldId {get;set;}
public string Value {get;set;}
public string Operator {get;set;}
}
所以...如果我將以下 JSON 發布到我的端點
{ "pageSize":10, "query": { "fieldId": "body", "value": "cake", "operator": "matches" } }
我成功獲得了一個搜索物件,但 Query 屬性的型別是 Expression,而不是 MatchesExpression。
這顯然是一個多型問題。
這篇文章(接近尾聲)給出了一個很好的例子,說明當你的整個模型都是多型時如何處理這個問題。
https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-5.0
就我而言,我的模型“查詢”的屬性是多型的,所以我不確定如何為我的 Search 物件構建一個 ModelBinder,這將允許我處理 Query 屬性
我想象一下,我需要撰寫一個模型系結器來構造搜索物件,然后遵循為該屬性描述的模式,但是我找不到任何關于如何實作模型系結器的示例,這不是完全微不足道的。
關于如何實作這一目標的任何建議?良好的資訊來源?
uj5u.com熱心網友回復:
所以..我放棄了 ModelBInders(因為我使用了與我的目標不兼容的 FromBody 屬性)。
相反,我撰寫了一個 System.Text.Json JsonConvertor 來處理多型性(請參閱下面的 shonky 代碼)
using Searchy.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Searchy
{
public class ExpressionJsonConverter : JsonConverter<Expression>
{
public override Expression Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Utf8JsonReader readerClone = reader;
using (var jsonDocument = JsonDocument.ParseValue(ref readerClone))
{
if (!jsonDocument.RootElement.TryGetProperty("type", out var typeProperty))
{
throw new JsonException();
}
switch (typeProperty.GetString())
{
case "comparison":
return JsonSerializer.Deserialize<Comparison>(ref reader, options);
case "and":
return JsonSerializer.Deserialize<And>(ref reader, options);
}
}
return null;
}
public override void Write(
Utf8JsonWriter writer,
Expression expression,
JsonSerializerOptions options)
{
}
}
}
我的 Expression 類也有以下屬性
[JsonConverter(typeof(ExpressionJsonConverter))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/317621.html
標籤:asp.net asp.net核心 asp.net-web-api
