3

I am working in an asp.net application trying to write a JSON.Net query to write (POST) a record to an API. However, I am having trouble trying to figure out how to format the json string in order to pass it to the API.

The "Example" on the vendor's support page has the following header information.

POST /extact/api/profiles/114226/pages/423833/records HTTP/1.1
Host: server.iPadDataForm.com
Authorization: Bearer 6bfd44fbdcdddc11a88f8274dc38b5c6f0e5121b
Content-Type: application/json
X-IFORM-API-REQUEST-ENCODING: JSON
X-IFORM-API-VERSION: 1.1  

Question:
If I am using JSON.Net, how do I get the header information passed to the API ? I have looked at json.net website, but nothing has worked yet.

Csharp
  • 2,916
  • 16
  • 50
  • 77

2 Answers2

4

JSON.NET is library for serializing and deserializing .NET objects to JSON. It has nothing to do with sending HTTP requests. You could use a WebClient for this purpose.

For example here's how you could call the API:

string url = "http://someapi.com/extact/api/profiles/114226/pages/423833/records";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer 6bfd44fbdcdddc11a88f8274dc38b5c6f0e5121b";
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    client.Headers["X-IFORM-API-REQUEST-ENCODING"] = "JSON";
    client.Headers["X-IFORM-API-VERSION"] = "1.1";

    MyViewModel model = ...
    string jsonSerializedModel = JsonConvert.Serialize(model); // <-- Only here you need JSON.NET to serialize your model to a JSON string

    byte[] data = Encoding.UTF8.GetBytes(jsonSerializedModel);
    byte[] result = client.UploadData(url, data);

    // If the API returns JSON here you could deserialize the result
    // back to some view model using JSON.NET
}

The UploadData method will send an HTTP POST request to the remote endpoint. If you want to handle exceptions you could put it in a try/catch block and catch WebException which is what this method could throw if for example the remote endpoint returns some non 2xx HTTP response status code.

Here's how you could handle the exception and read the remote server response in this case:

try
{
    byte[] result = client.UploadData(url, data);
}
catch (WebException ex)
{
    using (var response = ex.Response as HttpWebResponse)
    {
        if (response != null)
        {
            HttpStatusCode code = response.StatusCode;
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                string errorContent = reader.ReadToEnd();
            }
        }
    }
}

Notice how in the catch statement you could determine the exact status code returned by the server as well as the response payload. You could also extract the response headers.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • @Darin, I am getting "Unauthorized" at client.UploadData(url, data). The token API is correct. Any ideas on that? – Csharp Aug 28 '13 at 12:36
  • I guess you provided an invalid/expired Bearer OAuth token. You seem to mention in your comment that the token is correct but what makes you think so if the API doesn't accept it and throws 401? – Darin Dimitrov Aug 28 '13 at 14:33
  • well, the token displayed above is inaccurate (for security). The token I have (in my application) is correct and has been verified with the vendor. The vendor is a non-.net shop, so they are not able to provide .net support – Csharp Aug 29 '13 at 19:08
  • I've never doubted about that. The code shown here should perform the correct HTTP request. – Darin Dimitrov Sep 03 '13 at 17:08
0

Use Web API or the MVC API.

If you want to know the difference.

http://encosia.com/asp-net-web-api-vs-asp-net-mvc-apis/

ASP.NET Web API vs. ASP.NET MVC “APIs” by Dave Ward

In Short the differences are:

Content negotiation Flexibility Separation of concerns

Pinch
  • 4,009
  • 8
  • 40
  • 60