0

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

12
  • How about to remove one bracket? Commented Dec 15, 2017 at 21:27
  • This may not be the answer, I'm not sure.. But it looks like you're sending an object within an object. Your JSON has two opening and two closing brackets. Try removing one from each and maybe that will help? Commented Dec 15, 2017 at 21:29
  • You should create a model to match the JSON, Then use it as input into the endpoint with the [FromBody] decorator. Then it will come into the function in JSON and you can Deserialize to the model. Commented Dec 15, 2017 at 21:34
  • Just FYI. At first glance, it looks like you're trying to create a RESTful API. But when you try to pass an entire JSON structure in as part of the makeup of the URL, you break REST. You really want to send a POST request, and have the JSON be that body of that request. Commented Dec 15, 2017 at 21:42
  • @BrandonMiller I will try with remove one bracket. May i know how to receive the Json string in api. Commented Dec 15, 2017 at 21:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am sending the JSON string from an WPF application. Do i need to create model in WPF or Web API. I am new to RESTAPI, can you please give me an example how to send it from WPF application. Thanks
@user2086641 You should create model I shown above in your Web API project. Unfortenly, I'm not WPF developer, just try to find examples related to classes you use to send data (probably, it's WebClient or HttpResponseMessage). Also, it's good (common) practice to have models on both sides (client and server). In case you will create model in your WPF app and Web API backend your flow will look like: 1. You are preparing model and serializing it in WPF app; 2. WPF app makes API call. 3. Web API catch request and deserialize ОЫЩТ under the hood; 4. Web API executes your logic and return result.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.