从WebAPi调用REST服务并传输HttpResponseMessage

时间:2017-06-01 12:25:37

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

我必须从Web API调用REST服务。 调用和检索数据运行良好但返回方法崩溃。 我已经尝试了几个返回async HttpResponseMessage的方法,但我也可以返回此对象(chrome ERR_SPDY_PROTOCOL_ERROR上的错误套接字)。 我也尝试过只用普通的json作为字符串,但没有更多的成功。

这里有些尝试:

    [Route("{id}")]
    public async Task<JObject> Get(string id)
    {
        dynamic client = new RestClient($"https://...../accounts/{id}/summary",
            new Dictionary<string, string> {
                //some KVP for access Rest API
            });
//await client.Get() returns HttpResponseMessage 200 and Content is well populated

        JObject result =  JObject.FromObject(await client.Get());
        return result;
        //Request.CreateResponse(HttpStatusCode.OK, await result.Content.ReadAsAsync<string>());

        //HttpResponseMessage result = await client.Get(); => HttpResponseMessage is well filled
        //Request.CreateResponse(HttpStatusCode.OK, await result.Content.ReadAsAsync<string>()); => test with wrapping inside a new HttpResponseMessage but no more success



        //using (var client = new HttpClient())
        //{
        //    client.BaseAddress = new Uri($"https://....../v1/accounts/{id}/summary");
        //    client.DefaultRequestHeaders.Accept.Clear();
        //    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


        //    HttpResponseMessage response = await client.GetAsync("");
        //    return Request.CreateResponse(HttpStatusCode.OK, response.Content.ReadAsAsync());
        //}
    }

是否有一种简单的方法可以从Rest Service中检索json并按原样传输它?

2 个答案:

答案 0 :(得分:1)

如果您只想从其他API传输json响应,可以在Web API中使用以下代码:

[HttpGet]
    [Route("v1/test", Name = "test")]
    public HttpResponseMessage GetTest()
    {
        UriBuilder uriBuilder = new UriBuilder($"https://...../...");
        var webRequest = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri);
        webRequest.Method = "GET";
        webRequest.ContentType = "application/json; charset=utf-8";
        webRequest.Accept = "application/json, text/javascript, */*";
        using (var jsonResponse = (HttpWebResponse) webRequest.GetResponse())
        {
            var jsonStream = jsonResponse.GetResponseStream();

            MemoryStream ms = new MemoryStream();
            jsonStream.CopyTo(ms);
            ms.Position = 0;
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(ms);
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            return response;
        }            
    }

当唯一需要的是支持身份验证或授权功能时,我更愿意使用API​​管理器而不是自己维护这种代码。

答案 1 :(得分:1)

如果这些调用是在Web API中执行的,并且没有逻辑应用于JSON对象,那么在返回它之前几乎不需要解析它,因为它会在返回时再次被序列化,你可以改为在前端应用程序上解析它并在那里执行你的逻辑。

HttpClient有一个方法,它将响应主体作为字符串返回,这是GetStringAsync。将正文作为字符串返回后,您可以直接在HttpResponseMessage

中返回

以下是使用HttpClient注释代码的示例。

[Route("{id}")]
public async Task<HttpResponseMessage> Get(string id)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri($"https://....../v1/accounts/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // Fetch the response body as a string
        // Resource URI added below
        string responseContent = await client.GetStringAsync($"{id}/summary");

        // Create our response object and set the content to its StringContent
        var response =
            new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(responseContent)};

        // Return our HttpResponseMessage containing our json text
        return response;
    }
}