我正在嘗試將要從 Angular 13 中洗掉的物件的多個 ID 發送到我的 C# .net API。
通過在線研究,這是建議使用 http.delete 發送正文的方法,這將需要回傳更新的演出費用。
我的第一個問題是,這是通過 RESTful API 呼叫此方法的適當方式嗎?
deleteMultipleReturnShowCosts(showId: number, objs: number[]): Observable<ShowCost[]>{
const options = { headers: new HttpHeaders({'Content-Type': 'application/json'}),
body: { ids: JSON.stringify({...objs})}};
return this.http.delete<ShowCost[]>(`${this.url}/${showId}`, options)
.pipe(
catchError(this.handleError<ShowCost[]>('Delete: Show Item'))
);
}
例如,在這個方法中,我發送objs: number[] of [151,152,153]
這是我的 C# API 洗掉方法的當前測驗代碼
/// <summary>
/// Delete Show Item
/// </summary>
/// <param name="ids"></param>
/// <param name="showId"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpDelete("{showId:int}", Name = nameof(DeleteShowItem))]
public async Task<IActionResult> DeleteShowItem([FromBody] object jsonObj, int showId)
{
try
{
var jsonString = JsonConvert.SerializeObject(jsonObj);
var jsonKeyValuePair = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
jsonKeyValuePair.TryGetValue("ids", out var stringArray);
if (stringArray == null) return BadRequest("Array did not parse.");
var showItemIds = JsonConvert.DeserializeObject<int[]>(stringArray);
return Ok();
}
catch (Exception e)
{
_logger.LogError(e.Message);
return BadRequest(e.Message);
}
}
我一直試圖以許多不同的方式分解物體,但沒有任何樂趣。
這些是當前變數值:
json物件
{
"ids": "{\"0\":151,\"1\":152,\"2\":153}"
}
jsonKeyValuePair
Count = 1
key[0] = ids
value[0] = {"0":151,"1":152,"2":153}
showItemIds
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Int32[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path '0', line 1, position 5.
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at Assembly2021.API.Controllers.ShowItemController.DeleteShowItem(Object jsonObj, Int32 showId) in /Users/alexanderlynn/RiderProjects/assembly2021-angular/Assembly2021-API/Assembly2021.API/Controllers/ShowItemController.cs:line 182
最終,我想為 API 呼叫的其余部分獲取一個 IEnumerable。
提前致謝!
uj5u.com熱心網友回復:
您可以通過將您的 json 更改為一個陣列而不是那個奇怪的物件來簡化這一點,而不是:
body: { ids: JSON.stringify({...objs})}};
寫
body: objs };
json 將變成一個簡單的陣列:
[ 1,2,3,4 ]
在 api 中,只需將您的引數宣告為可以接受物件串列的東西,例如陣列或串列或 IEumerable:
public async Task<IActionResult> DeleteShowItem([FromBody] int[] jsonObj, int showId)
開箱即用不需要額外的代碼。
也不要將 catch 日志邏輯烘焙到所有端點中
catch (Exception e)
{
_logger.LogError(e.Message);
return BadRequest(e.Message);
}
你已經做錯了只記錄訊息關于例外的最重要的事情是堆疊跟蹤第二個是來自最內部例外的訊息。你這樣做的方式會阻礙你發現錯誤的能力。因此,記錄完整例外,您的記錄器應該接受 Exception 作為引數,或者至少將 e.ToString() 傳遞給它。為了不重復此代碼,請撰寫一個操作過濾器。并且錯誤請求適用于用戶使用無效引數呼叫您的端點:) 現在對于您的代碼的每一個錯誤,您都在責怪用戶:)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437099.html
