C# HttpClient PostAsync 403 forbidden with SSL。

问题描述 投票:0回答:1

自从我们切换到SSL服务器后,当我进行POST时,我总是收到一个403 forbidden的错误,但如果我使用WebClient,它可以正常工作,无论如何,我还是想让它与HttpClient一起工作,因为我必须改变很多代码,而且有一个使用MultipartFormDataContent来发布文件的调用,我不能用WebClient来做,在Webclient中,我可以选择POST数据或上传文件,但我需要在一次调用中发布数据和文件。

下面是一个HttpClient和WebClient调用的例子。

HttpClient (403 forbidden error)

 private async void Login_Click(object sender, RoutedEventArgs e)
    {
        Apic = CryptoEngine.DecryptAPI(Apic);
        if (API())
        {
            using (var content = new MultipartFormDataContent())
            {
                if (EmailText.Text.Contains("@") && EmailText.Text.Contains("."))
                {
                    content.Add(new StringContent(EmailText.Text), "\"email\"");
                }
                else
                {
                    content.Add(new StringContent(EmailText.Text), "\"username\"");
                }

                content.Add(new StringContent(PasswordText.Password), "\"password\"");
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Clear();
                    httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json");
                    httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
                    httpClient.DefaultRequestHeaders.Add("appName", "CloudMetaPrinter");
                    httpClient.DefaultRequestHeaders.Add("latitude", Apic.Latitude);
                    httpClient.DefaultRequestHeaders.Add("longitude", Apic.Longitude);
                    httpClient.DefaultRequestHeaders.Add("hostname", Apic.IP);
                    httpClient.DefaultRequestHeaders.Add("hostType", "PC");
                    var httpResponse = httpClient.PostAsync(url + "/" + api + "/auth/login", content);
                    responseContent = await httpResponse.Result.Content.ReadAsStringAsync();
                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);

WebClient(工作正常)

private void Login_Click(object sender, RoutedEventArgs e)
    {
        Apic = CryptoEngine.DecryptAPI(Apic);
        if (API())
        {
            string data;
            if (EmailText.Text.Contains("@"))
            {
                data = JsonConvert.SerializeObject(new
                {
                    email = EmailText.Text,
                    password = PasswordText.Password
                });
            }
            else
            {
                data = JsonConvert.SerializeObject(new
                {
                    username = EmailText.Text,
                    password = PasswordText.Password
                });
            }
            using (var httpClient = new WebClient { UseDefaultCredentials = true })
            {
                httpClient.Headers.Add("appName", "CloudMetaPrinter");
                httpClient.Headers.Add("latitude", Apic.Latitude);
                httpClient.Headers.Add("longitude", Apic.Longitude);
                httpClient.Headers.Add("hostname", Apic.IP);
                httpClient.Headers.Add("hostType", "PC");
                httpClient.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
                var httpResponse = httpClient.UploadData(url + "/" + api + "/auth/login", "POST", Encoding.UTF8.GetBytes(data));
                var str = System.Text.Encoding.Default.GetString(httpResponse);
                Result result = JsonConvert.DeserializeObject<Result>(str);

我试着在头中做了一些改动,UseDefaultCredentials=true等等,但都没有用。

Edit: im using .net core 3.0Edit2: The GetAsync with HttpClient works fine, the problem is only with PostAsync.

好吧,所以我试着与fiddler比较,并改变了一些东西,所以httpclient调用更像webclient,但仍然得到403Left是WebClient,右边是HttpClient。比较图片

c# visual-studio
1个回答
1
投票

你需要通过一个 HttpClienthandler 对象的构造函数中。HttpClient. 该 UseDefaultCredentials 财产已移至 HttpClienthandler

例子。

   using(var handler = new HttpClientHandler())
   {
      handler.UseDefaultCredentials = true;

      using(var client = new HttpClient(handler))
      {

         var response = await client.GetAsync("http://www.contoso.com/");
         response.EnsureSuccessStatusCode();

         var responseBody = await response.Content.ReadAsStringAsync();
   }

(请注意,这样做的效率可能会很低。Dispose()HttpClient 经常使用,最好是重复使用)。)

https:/docs.microsoft.comen-usdotnetapisystem.net.http.httpclienthandler?view=netcore-3.

© www.soinside.com 2019 - 2024. All rights reserved.