简体   繁体   中英

Consuming WebAPI JSON

I'm trying to build some kind of RESTful-like API, I'm aware of that my first draft probably isn't anything near the real RESTful design pattern. However my real question is how should I consume my service using JSON?

In my so called real world example I want my users to sign in via the service so I have this AuthenticationController

namespace RESTfulService.Controllers
{
    public class AuthenticationController : ApiController
    {

        public string Get(string username, string password)
        {
            // return JSON-object or JSON-status message
            return "";
        }

        public string Get()
        {
            return "";
        }

    }
}

Considering the increasing popularity with the technology I assumed that very little code would be needed for consuming the service. Do I really need to serialize the JSON manually with some kind of third party package like json.net? Beneath is my draft for the client

private static bool DoAuthentication(string username, string password)
{
    var client = InitializeHttpClient();

    HttpResponseMessage response = client.GetAsync("/api/rest/authentication").Result;  
    if (response.IsSuccessStatusCode)
    {

        //retrieve JSON-object or JSON-status message

    }
    else
    {
        // Error
    }

    return true;
}

private static HttpClient InitializeHttpClient()
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost/");

    // Add an Accept header for JSON format.
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

    return client;
}

How do I send JSON from service and how do I interpreting it on the client?

Have a look at the System.Net.Http.HttpContentExtensions in System.Net.Http.Formatting.dll. As explained here (and suggested by Mike Wasson in a comment above), you can call ReadAsAsync<T>() on the response content to deserialize from JSON (or XML) to a CLR type:

if (response.IsSuccessStatusCode)
{
    var myObject = response.Content.ReadAsAsync<MyObject>();
}

If you need to customize the deserialization, that article links to a further explanation of MediaTypeFormatters.

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