使用创建的HttpWebResponse接口返回401 Unauthorized Error

时间:2017-04-03 14:02:59

标签: c# .net unit-testing httpwebrequest http-status-code-401

所以我最初有这个代码用于网络请求:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.UseDefaultCredentials = true;
WebResponse response = request.GetResponse();

我更改为此以添加单元测试:

IHttpWebRequest request = IHttpWebRequestFactory.Create(uri);
request.UseDefaultCredentials = true;
IWebResponse response = request.GetResponse();

IHttpWebRequest:

public interface IHttpWebRequest
{
    bool UseDefaultCredentials { get; set; }
    IWebResponse GetResponse();
}

MyHttpWebRequest:

public class MyHttpWebRequest : IHttpWebRequest
{
    private readonly HttpWebRequest httpWebRequest;
    private bool useDefaultCredentials;

    public MyHttpWebRequest(HttpWebRequest httpWebRequest)
    {
        this.httpWebRequest = httpWebRequest;
    }

    public bool UseDefaultCredentials
    {
        get { return useDefaultCredentials;  }
        set { useDefaultCredentials = value; }
    }

    public IWebResponse GetResponse()
    {
        return new MyWebResponse((HttpWebResponse)httpWebRequest.GetResponse());
    }
}

IHttpWebRequestFactory:

public interface IHttpWebRequestFactory
{
    IHttpWebRequest Create(string Uri);
}

HttpWebRequestFactory:

public class HttpWebRequestFactory : IHttpWebRequestFactory
{
    public IHttpWebRequest Create(string Uri)
    {
        return new MyHttpWebRequest((HttpWebRequest)WebRequest.Create(Uri));
    }
}

IWebResponse:

public interface IWebResponse
{
    Stream GetResponseStream();
}

MyWebResponse:

public class MyWebResponse : IWebResponse
{
    private WebResponse webResponse;

    public MyWebResponse(HttpWebResponse webResponse)
    {
        this.webResponse = webResponse;
    }

    public Stream GetResponseStream()
    {
        return webResponse.GetResponseStream();
    }
}

但该网站现在返回HTTP错误401未经授权。然而,使用Fiddler工作。我也尝试过设置request.Credentials = CredentialCache.DefaultNetworkCredentialsrequest.PreAuthenticate = true等,但无济于事。 :(

我还尝试将我的用户名和密码提供给凭据,但仍然会出现未经授权的错误,这是奇怪的,因为上面的原始代码有效。 :(

1 个答案:

答案 0 :(得分:0)

您没有正确使用useDefaultCredentials,请尝试以下操作:

MyHttpWebRequest:

public class MyHttpWebRequest : IHttpWebRequest
{
    private readonly HttpWebRequest httpWebRequest;

    public MyHttpWebRequest(HttpWebRequest httpWebRequest)
    {
        this.httpWebRequest = httpWebRequest;
    }

    public bool UseDefaultCredentials
    {
        get { return this.httpWebRequest.UseDefaultCredentials;  }
        set { this.httpWebRequest.UseDefaultCredentials = value; }
    }

    public IWebResponse GetResponse()
    {
        return new MyWebResponse((HttpWebResponse)httpWebRequest.GetResponse());
    }
}