简体   繁体   中英

Receiving the key value pair as input parameter

I am trying to receive the below key value pair as the input parameter to my Web API

json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A

where the right of the string is the URL encoded JSON which looks like

{
"MouseSampleBarcode" : "MOS81"
}

How can I parse this and store them in to the Model class

 [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();

where the CoreBarCodeDTO looks like below

public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }

You could do it this way. Change your class to this definition. In your controller coreBarCode.json will have the the json which you can then work with as needed:

public class CoreBarCodeDTO
{
    private string _json;
    public string json { get { return _json; }
        set {
            string decoded = HttpUtility.UrlDecode(value);
            _json = decoded;
        }
    }
}

Update

 [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"

 }

As @Lokki mentioned in his comment. The GET verb does not have a body, you need to change that to POST or PUT (depending if you are creating/searching or updating), so your code would look like this:

[HttpPost("/")]
public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{ 
   string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();

So, as I said: Get doesn't have body.
Follow @KinSlayerUY answer.

[HttpPost("/")]
public async Task<IHttpActionResult> Post([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{ 
   string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
   ...
}


If you need use GET remove [FromBody] attribute and send data as single parameters

[HttpGet("/")]
public async Task<IHttpActionResult> Get(string mouseSampleBarcode)
{ 
   var rootObject = new CoreBarCodeDTO.RootObject
   {
        MouseSampleBarcode = mouseSampleBarcode
   }
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM