HttpWebRequest有效,但HttpClient没有?

时间:2015-08-25 16:17:57

标签: c# asp.net

我尝试连接第三方WebApi并创建了多个单元测试来确定所述WebApi的功能。我的初始测试使用了System.Net并做了类似以下的事情......

var request = (HttpWebRequest)WebRequest.Create(commonUrl +
    "api/controller/action?value=" + value);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;
request.Method = "POST";
var response = (HttpWebResponse)request.GetResponse();

这会返回一个预期的响应,一切正常,但后来我被要求使用System.Net.Http,所以尝试以下内容......

HttpClient client = new HttpClient() { BaseAddress = new Uri(commonUrl) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(
    "application/x-www-form-urlencoded"));
var postData = new List<KeyValuePair<string, string>>() 
{ 
    new KeyValuePair<string, string>("value", value) 
};
var response = client.PostAsync("api/controller/action", 
    new FormUrlEncodedContent(postData)).Result;

不幸的是,回复StatusCode回复System.Net.HttpStatusCode.NotFound知道为什么会这样吗?

提前致谢

0 个答案:

没有答案