简体   繁体   中英

Can't get a valid response from a REST web service using System.Net.Http.HttpClient

I am using this test method (and helper class) to verify the response from an external web service:

[TestMethod]
public void WebServiceReturnsSuccessResponse()
{
    using (var provider = new Provider(new Info()))
    using (var result = provider.GetHttpResponseMessage())
    {
        Assert.IsTrue(result.IsSuccessStatusCode);
    }
}

private class Info : IInfo
{
    public string URL { get; set; } =
        "https://notreallythe.website.com:99/service/";
    public string User { get; set; } = "somename";
    public string Password { get; set; } = "password1";
}

I can't get this test to pass; I always get a 500 - Internal Server Error result. I have connected via an external utility (Postman) - so the web service is up and I can connect with the url & credentials that I have.

I think the problem is in my instantiation of the HttpClient class, but I can't determine where. I am using Basic authentication:

public class Provider : IProvider, IDisposable 
{
    private readonly HttpClient _httpClient;

    public Provider(IInfo config){
        if (config == null) 
           throw new ArgumentNullException(nameof(config));

        var userInfo = new UTF8Encoding().GetBytes($"{config.User}:{config.Password}");

        _httpClient = new HttpClient
        {
            BaseAddress = new Uri(config.URL),
            DefaultRequestHeaders =
            {
                Accept = { new MediaTypeWithQualityHeaderValue("application/xml")},
                Authorization = new AuthenticationHeaderValue(
                   "Basic", Convert.ToBase64String(userInfo)),
                ExpectContinue = false,                 
            },
         };
    }

    public HttpResponseMessage GetHttpResponseMessage()
    {
        return _httpClient.GetAsync("1234").Result;
    }
}

The response I get back appears to go to the correct endpoint; the RequestUri in the response looks exactly like I expect, https://notreallythe.website.com:99/service/1234 .

You need to load up Fiddler and do a recording of the HTTP traffic when this operation succeeds (through the browser).

Then, load up your code, stand up another instance (or window) of Fiddler, and do the same thing with your code. Now, compare the two Fiddler windows to see what is different.

You only need to compare those things in Fiddler that are highlighted in blue. You can ignore the other communications.

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