mercredi 23 décembre 2015

Http client always returns 404 if I do not use a http://localhost

Have a web api that works no problem if I call it from a browser.

I wanted to use HttpClient to call it:

 private const string BaseAddress = "http://ift.tt/1O9PAYA";

    private static readonly HttpClient HttpClient = new HttpClient();



    public static string PostAsJsonAsync(string route, Object jsonConverterParam)
    {

        string result = String.Empty;
        string jsonSerializable = JsonConvert.SerializeObject(jsonConverterParam, Formatting.Indented);
        JObject postContent = JObject.Parse(jsonSerializable);

        try
        {
            var fullRoute = PrepareHttpRequest(route);
            using (HttpResponseMessage response = HttpClient.PostAsJsonAsync(fullRoute, postContent).Result)
            {
                result = response.Content.ReadAsStringAsync().Result;
                DumpUtils.DumpDataToFile(route, fullRoute, postContent, result, response);
                response.EnsureSuccessStatusCode();
            }
        }
        catch (Exception ex)
        {
            throw new HttpRequestException(result, ex);
        }

        return result;
    }
    private static string PrepareHttpRequest(string route)
    {

        HttpClient.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
        string requestUri = BaseAddress + route;
        return requestUri;
    }

This code works fine in the dev environment where the baseurl is a http://localhost address. However, as soon as I change the baseUrl to say http://ift.tt/1O9PAYA I get a 404. If I use a browser and enter say http://ift.tt/1O9PAYA (the URI the code constructs) the API call works as expected.




Aucun commentaire:

Enregistrer un commentaire