Receiving Json string in Web API controller

2019-08-17 17:15发布

Following is my Json input string from WPF app,

{{
  "Country of Origin": "UNITED STATES",
  "Commodity": "APPLES",
  "Variety": "Green",
  "Upcs": [
    {
      "timestamp": "2017-09-19T21:05:12.8550708+05:30",
      "value": "038452735329R5"
    },
    {
      "timestamp": "2017-09-19T21:05:12.8550708+05:30",
      "value": "038452735330R5"
    }
  ],
  "ipAddress": "127.0.0.1",
  "lat": "155.00",
  "Lot": "101.14",
  "long": "-202.00",
  "onBehalfOf": "679",
  "ClientVersion": "10.0.7",
  "submittedBy": "679"
}}

I have created a Rest Api2 app in .net (VS2015) and i want to receive the above JSON string in my newly created API for furthur processing.

In WPF, i am using WebClient to send the Json string.

Below is the API function I tried to receive the Json string,

    [Route("api/events/getevents/{events}/{producerId}")]
    [HttpGet, HttpPost]
    public async Task<IHttpActionResult> GetEvents(string events, string producerId)
    {
        try
        {
            await _getEventsAction.GetEventJson(events, producerId).ConfigureAwait(false);
            return Ok("Success");
        }
        catch (AggregateException ex)
        {
            return Ok(new { ex.InnerException.Message, Success = false, ex.StackTrace, Exception = ex });
        }
        catch (Exception ex)
        {
            return Ok(new { ex.Message, Success = false, ex.StackTrace, Exception = ex });
        }
    }

After running the app in local, i tested the api in web browser by proving the following values that is, for events="testing" and producerId="554", the final endpoint looks like below,

http://localhost:18572/api/events/getevents/testing/554 -> this case the endpoint works fine in browser. But for testing the above api, instead of testing, when i input the whole Json string in browser web address, browser is showing the error as "A potentially dangerous Request.Path value was detected from the client (:)." . This is due to the double quotes and colon in between the json string, browser is showing the error page.

Screen below,

enter image description here

  1. I want to know, the API function what i developed is correct to receive the Json string. If any good way please guide me.

  2. May i know what are the better way i can test this API by input the Json string.

  3. Is it possible to receive the Json as object in api.

Please help me in writing this API to receive the Json string or Json object.

Thanks

1条回答
欢心
2楼-- · 2019-08-17 17:35

Normally, in cases when you need to send JSON, you should make POST/PUT request and send JSON in the request body.

To do so:

  1. You need to create model which matches your JSON:

    [DataContract]
    public class MyModel
    {
        [DataMember(Name = "Country of Origin")]
        public string CountryOfOrigin { get; set; }
    
        [DataMember(Name = "Commodity")]
        public string Commodity { get; set; }
    
        // other fields
    }
    

    Also, note I used DataContract and DataMember attributes as incoming JSON fields not normalized (fields has spaces and different case (camelCase and CamelCaps)).

    If you will normalize your JSON to camelCase, you may remove DataContract and DataMember attributes.

  2. Change action in controller to:

    [Route("api/events/getevents/{events}/{producerId}")]
    [HttpPost]
    public async Task<IHttpActionResult> GetEvents(string events, string producerId, [FromBody] MyModel model)
    {
        // your code
    }
    

    Last "model" parameter will be populated with values you send from client.

    [HttpPost] attribute indicates that this action will be available only with POST requests.

    [FromBody] attribute indicates that Web API should take model from request's body.

查看更多
登录 后发表回答