让WebAPI Controller将http请求发送到另一个REST服务

时间:2018-06-15 20:49:47

标签: c# json asp.net-web-api2 asp.net-core-webapi

我正在创建WebAPI服务,我希望它将所有传入请求(GET,POST)重定向到外部REST服务,并将响应(Json / html)返回到我的WebAPI的原始请求。

这样做的最佳方法是什么? HttpResponseMessage或HttpWebResponse

    [HttpGet]
    [Route("api/Geocoder")]
    public HttpWebResponse GetCandidates(string query)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://externalRestService.com/arcgis/rest/services/Geocode" + query);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        return response;

    }

我也试过

    [HttpGet]
    public HttpResponseMessage Get()
    {
        try
        {
            HttpClient httpClient = new HttpClient()
            {
                BaseAddress = new Uri(""https://externalRestService.com/arcgis/rest/services/Geocode")
            };

            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            response = httpClient.GetAsync(requestUrl).Result;
            return response;
        }
        catch
        {
            return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.InternalServerError,
                ReasonPhrase = "Internal Server Error"
            };
        }

    }

提前感谢您的帮助。我是.Net Core和webapis的新手

1 个答案:

答案 0 :(得分:1)

以下方法对我有用。

public async Task<IHttpActionResult> GET(string query)
    {
        string _apiUrl = "http://foo.com/rest/services/Geocode?"; 
        string _baseAddress = "http://foo.com/rest/services/Geocode?";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_baseAddress);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var responseMessage = await client.GetAsync(_apiUrl + query);

            if (responseMessage.IsSuccessStatusCode)
            {
                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = responseMessage.Content;
                return ResponseMessage(response);
            }
        }
        return NotFound();
    }