C#WebApi HttpClient未经授权

时间:2016-02-11 08:46:30

标签: httpclient webclient unauthorized

我有一个关于 webapi2 和授权的问题 如果我用旧的.Net 2.0客户端(WebClient)调用web api,则没有问题,代码在这里:

//old 2.0 client
using (WebClient oldClient = new WebClient())
{
    oldClient.UseDefaultCredentials = true;
    oldClient.Credentials = CredentialCache.DefaultCredentials;
    oldClient.Headers[HttpRequestHeader.ContentType] = "application/json";
    oldClient.Headers[HttpRequestHeader.Accept] = "application/json";

    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    javaScriptSerializer.MaxJsonLength = 2147483644;

    ASCIIEncoding encoding = new ASCIIEncoding();
    string objectToSendJson = javaScriptSerializer.Serialize(objectToSend);
    byte[] objectToSendByte = encoding.GetBytes(objectToSendJson);
    byte[] serviceOutput = oldClient.UploadData(uri + actionController, "POST", objectToSendByte);

    string jsonStr = Encoding.UTF8.GetString(serviceOutput);

    toReturn = JsonConvert.DeserializeObject<T>(jsonStr);
    return toReturn;
} 

但是如果我使用新的4.5 HttpClient WebApi则返回未经授权 代码在这里:

HttpClientHandler httpWebApiClienthandler = new HttpClientHandler
{
    UseDefaultCredentials = true,
    Credentials = CredentialCache.DefaultCredentials,
};

System.Net.Http.HttpClient newHttpClient = new System.Net.Http.HttpClient(httpWebApiClienthandler)

//new 4.5 client
JsonMediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();

if (objectToSend == null)
    throw new Exception("object to send is null");

HttpContent httpContent = new ObjectContent<object>(objectToSend, jsonFormatter);
httpContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
response = newHttpClient.PostAsync(actionController, httpContent).Result;

非常感谢任何帮助。

0 个答案:

没有答案