Rub*_*aus 7 c# asp.net-web-api blazor-webassembly
我正在使用我的第一个 Blazor 应用程序并遇到一个奇怪的问题。我有一个 Web API,它返回一个相当基本的 JSON 响应:
{
"entityId": 26,
"notifications": [
{
"type": "Success",
"message": "The operation completed successfully."
}
],
"hasErrors": false,
"hasWarnings": false
}
Run Code Online (Sandbox Code Playgroud)
有一个标准的 POCO 类与上述属性相匹配。从 Blazor 应用程序中,当我尝试从 an 获取响应时Http.PutAsJsonAsync<T>,会创建 POCO 类的实例(因此它不为 null 并且不会引发错误),但上述值实际上都不存在。该EntityId属性为 null 并且Notifications已实例化但为空。我尝试访问响应的方式是:
var result = await Http.PutAsJsonAsync<ManufacturerModel>($"manufacturers", (ManufacturerModel)context.Model);
if (result.IsSuccessStatusCode)
{
var response = await JsonSerializer.DeserializeAsync<EntityResponseModel>(result.Content.ReadAsStream());
//response isn't null - it's just a newly created object with nothing mapped
}
Run Code Online (Sandbox Code Playgroud)
通过 Chrome 中的控制台,我已经确认返回了正确的 JSON,所以它真的很令人困惑为什么它会创建该类的新实例,但不映射任何值。
有任何想法吗?
**** 编辑 - 包括 POCO 定义 ****
public class EntityResponseModel : BaseModel
{
/// <summary>
/// Gets or sets the Id of the affected entity
/// </summary>
public long? EntityId { get; set; }
}
public class BaseModel
{
public BaseModel()
{
this.Notifications = new EntityNotificationCollection();
}
#region Validation
/// <summary>
/// Adds a notification to this model.
/// </summary>
/// <param name="type">The type of notification</param>
/// <param name="message">The message to display</param>
public void AddNotification(EntityNotificationTypes type, string message)
{
this.Notifications.Add(new EntityNotification { Type = type, Message = message });
}
/// <summary>
/// Gets or sets the collection of notifications
/// </summary>
public EntityNotificationCollection Notifications { get; private set; }
/// <summary>
/// Gets whether errors exist on this model.
/// </summary>
//[JsonIgnore]
public bool HasErrors { get => this.Notifications.HasErrors; }
/// <summary>
/// Gets whether warnings exist on this model
/// </summary>
//[JsonIgnore]
public bool HasWarnings { get => this.Notifications.HasWarnings; }
#endregion
}
Run Code Online (Sandbox Code Playgroud)
小智 10
您可以指定序列化设置并将其定义为区分大小写或不区分大小写。CharlieFace 在上面提供了这个答案。
看起来您需要添加 JsonAttribute 来管理大小写敏感性。
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
Run Code Online (Sandbox Code Playgroud)
这是我的完整解决方案:
var retList = new List<PocoSomeClassData> ();
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode) {
using (var reponseStream = await response.Content.ReadAsStreamAsync())
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
retList = await JsonSerializer.DeserializeAsync < List<PocoSomeClassData> > (reponseStream,options);
}
}
Run Code Online (Sandbox Code Playgroud)