将 Json 对象发布到 ASP 网络核心 API
Posting Json object to ASP net core API
我正在向我的 ASP 网络核心 API 发布一个 Json 对象,该对象如下所示。
如何在后端接收它以便我可以访问每个键值对?
我在任何地方都找不到对这个问题不超过 4 年的具体回答。
这取决于你在后端使用什么:我在这里假设你使用的是 MVC,因此有端点。
当 posting JSON 到 C# 端点时,您很可能需要为此创建一个 C# 模型。
您发送的JavaScript型号:
{
productNumber: 'TEST',
allowedRStates: 'Allowed *',
productType: 'Type 1',
enableMachineLearningService: false,
productFamilyId: 1,
parentProductId: null,
addedDate: '2021-04-26 10:09:16.164',
modifiedDate: '2021-04-27 19:19:53.112',
productGuid: '345',
comPortAlias: 'RadioCool',
hwsEnableLogAnalysis: false
}
可以用 C# 建模 class 像这样:
namespace XYZ
{
using System;
using System.Linq;
public class SampleModel
{
#region properties
public string ProductNumber { get; set; }
public string AllowedRStates { get; set; }
public string ProductType { get; set; }
public bool EnableMachineLearningService { get; set; }
public long ProductFamilyId { get; set; }
public long ParentProductId { get; set; }
public DateTimeOffset AddedDate { get; set; }
public DateTimeOffset ModifiedDate { get; set; }
public string ProductGuid { get; set; }
public string ComPortAlias { get; set; }
public bool HwsEnableLogAnalysis { get; set; }
#endregion
}
}
在您的 C# 控制器中 class 您现在可以为 post 请求创建一个新端点:
...
[HttpPost("PostTest")]
public async Task<IActionResult> PostTest([FromBody] SampleModel model)
{
// Start to use your send data as 'model' from here on.
return Ok();
}
...
当您现在在 JavaScript 中为此新端点创建提取请求时,C# 会将 POST 正文 JSON 解析到新的 C# 模型中。从这一刻起,您可以像使用任何其他普通 C# 模型一样在 C# 端使用您的发送数据。
我正在向我的 ASP 网络核心 API 发布一个 Json 对象,该对象如下所示。
如何在后端接收它以便我可以访问每个键值对?
我在任何地方都找不到对这个问题不超过 4 年的具体回答。
这取决于你在后端使用什么:我在这里假设你使用的是 MVC,因此有端点。
当 posting JSON 到 C# 端点时,您很可能需要为此创建一个 C# 模型。
您发送的JavaScript型号:
{
productNumber: 'TEST',
allowedRStates: 'Allowed *',
productType: 'Type 1',
enableMachineLearningService: false,
productFamilyId: 1,
parentProductId: null,
addedDate: '2021-04-26 10:09:16.164',
modifiedDate: '2021-04-27 19:19:53.112',
productGuid: '345',
comPortAlias: 'RadioCool',
hwsEnableLogAnalysis: false
}
可以用 C# 建模 class 像这样:
namespace XYZ
{
using System;
using System.Linq;
public class SampleModel
{
#region properties
public string ProductNumber { get; set; }
public string AllowedRStates { get; set; }
public string ProductType { get; set; }
public bool EnableMachineLearningService { get; set; }
public long ProductFamilyId { get; set; }
public long ParentProductId { get; set; }
public DateTimeOffset AddedDate { get; set; }
public DateTimeOffset ModifiedDate { get; set; }
public string ProductGuid { get; set; }
public string ComPortAlias { get; set; }
public bool HwsEnableLogAnalysis { get; set; }
#endregion
}
}
在您的 C# 控制器中 class 您现在可以为 post 请求创建一个新端点:
...
[HttpPost("PostTest")]
public async Task<IActionResult> PostTest([FromBody] SampleModel model)
{
// Start to use your send data as 'model' from here on.
return Ok();
}
...
当您现在在 JavaScript 中为此新端点创建提取请求时,C# 会将 POST 正文 JSON 解析到新的 C# 模型中。从这一刻起,您可以像使用任何其他普通 C# 模型一样在 C# 端使用您的发送数据。