使用Web API JSON

时间:2013-06-01 10:16:27

标签: c# json asp.net-web-api

我正在尝试构建某种类似RESTful的API,我知道我的初稿可能不是真正的RESTful设计模式。但是我真正的问题是我应该如何使用JSON来使用我的服务?

在我所谓的真实世界示例中,我希望我的用户通过该服务登录,因此我有这个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 "";
        }

    }
}

考虑到该技术日益普及,我认为消耗服务所需的代码非常少。我是否真的需要使用某种第三方软件包(如json.net)手动序列化JSON? Beneath是我的客户草案

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;
}

如何从服务中发送JSON以及如何在客户端上解释它?

1 个答案:

答案 0 :(得分:0)

查看System.Net.Http.Formatting.dll中的System.Net.Http.HttpContentExtensions。正如解释here(以及Mike Wasson在上面的评论中所建议的),您可以在响应内容上调用ReadAsAsync< T>()以从JSON(或XML)反序列化为CLR类型:

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

如果您需要自定义反序列化,那么该文章将链接到MediaTypeFormatters的进一步说明。

相关问题