使用HttpClient Vs调用Web API时出现问题.WebClient C#

CSh*_*per 2 c# asp.net-web-api

我试图通过使用HttpClient但得到Not authorized错误来进行Web API调用.我在标题中传递密钥但仍然,它给了我这个错误.我可以看到我的钥匙fiddler trace.

如果我使用WebClient那么我会得到一个成功的回应.request两种方法都相同.

使用HttpClient:

#region HttpClient

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apiKey", "MyKey");

    var content = JsonConvert.SerializeObject(request);
    var response = await client.PostAsJsonAsync("https://MyUrl", content);

    if (response.IsSuccessStatusCode)
    {
        deliveryManagerQuoteResponse = await response.Content.ReadAsAsync<DeliveryManagerQuoteResponse>();
    }
    else
    {
        var reasonPhrase = response.ReasonPhrase;
        if (reasonPhrase.ToUpper() == "NOT AUTHORIZED")
        {
            throw new KeyNotFoundException("Not authorized");
        }
    }
}

#endregion
Run Code Online (Sandbox Code Playgroud)

使用WebClient:

#region WebClient

// Create string to hold JSON response
string jsonResponse = string.Empty;

using (var client = new WebClient())
{
    try
    {
        client.UseDefaultCredentials = true;
        client.Headers.Add("Content-Type:application/json");
        client.Headers.Add("Accept:application/json");
        client.Headers.Add("apiKey", "MyKey");

        var uri = new Uri("https://MyUrl");
        var content = JsonConvert.SerializeObject(request);

        var response = client.UploadString(uri, "POST", content);
        jsonResponse = response;
    }
    catch (WebException ex)
    {
        // Http Error
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            var webResponse = (HttpWebResponse)ex.Response;
            var statusCode = (int)webResponse.StatusCode;
            var msg = webResponse.StatusDescription;
            throw new HttpException(statusCode, msg);
        }
        else
        {
            throw new HttpException(500, ex.Message);
        }
    }
}

#endregion
Run Code Online (Sandbox Code Playgroud)

mac*_*ura 5

首先,你使用的是HttpClient错误.

其次,你是否正在使用提琴手看看这两个请求是什么样的?您应该能够看到标题看起来不同.现在您正在使用授权标题,它实际上会做一些与您想要的不同的事情.您只需添加一个常规的'ol标题:

client.DefaultRequestHeaders.Add("apiKey", "MyKey");
Run Code Online (Sandbox Code Playgroud)