我正在尝试接收下面的键值对作为我的Web的输入参数
json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A字符串的右边是URL编码的JSON,如下所示
{
"MouseSampleBarcode" : "MOS81"
}我如何解析它并将它们存储到Model类中
[HttpPost]
public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{
string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();其中的CoreBarCodeDTO如下所示
public class CoreBarCodeDTO
{
public class RootObject
{
public string MouseSampleBarcode { get; set; }
}
}发布于 2017-11-16 15:59:10
你可以这样做。将类更改为此定义。在您的控制器中,coreBarCode.json将拥有json,然后您可以根据需要使用该json:
public class CoreBarCodeDTO
{
private string _json;
public string json { get { return _json; }
set {
string decoded = HttpUtility.UrlDecode(value);
_json = decoded;
}
}
}更新
[HttpPost]
public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTOcoreBarCode coreBarCode)
{
string Bar_Code = coreBarCode.json;
//work with the JSON here, with Newtonsoft for example
var obj = JObject.Parse(Bar_Code);
// obj["MouseSampleBarcode"] now = "MOS81"
}发布于 2017-11-16 15:34:54
正如@Lokki在他的评论中提到的。GET动词没有正文,您需要将其更改为POST或PUT (取决于您是在创建/搜索还是更新),因此代码如下所示:
[HttpPost("/")]
public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{
string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();发布于 2017-11-16 15:48:59
所以,就像我说的: Get没有身体。
跟着@KinSlayerUY回答。
[HttpPost("/")]
public async Task<IHttpActionResult> Post([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{
string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
...
}如果需要使用GET,删除[FromBody]属性并将数据作为单个参数发送
[HttpGet("/")]
public async Task<IHttpActionResult> Get(string mouseSampleBarcode)
{
var rootObject = new CoreBarCodeDTO.RootObject
{
MouseSampleBarcode = mouseSampleBarcode
}
...
}https://stackoverflow.com/questions/47333305
复制相似问题