C# WebApi HttpClient Несанкционированный

У меня проблема с webapi2 и авторизацией.
Если я вызываю web api со старым клиентом.Net 2.0 (WebClient), проблем нет, и код здесь:

//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, верните мне Unauthorized и код здесь:

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 ответов

Другие вопросы по тегам