简体   繁体   English

使用HttpClient时如何解决302错误?

[英]How do I resolve 302 Error when using HttpClient?

I've created a custom DNN module that uses HTTPClient to send information to an external API. 我创建了一个自定义DNN模块,该模块使用HTTPClient将信息发送到外部API。 My HttpClient method is as follows: 我的HttpClient方法如下:

public static async Task<string> CreatePayerResponse()
    {
        var credentials = GetCredentials();
        var objEventLog = new EventLogController();
        var gatewaySettings = new GatewaySetting_ProPay();
        SignupResult_ProPay result = new SignupResult_ProPay();
        using (HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())))
        {
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            response.EnsureSuccessStatusCode();
            client.BaseAddress = new Uri("https://xmltestapi.propay.com/ProPayAPI/signup");
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string responseBody;
            GatewaySetting_ProPay gatewaySetting = new GatewaySetting_ProPay();
            SignupRequest payerRequest = new SignupRequest();
            HttpContent content = new StringContent(payerRequest.ToString());
            try
            {
                request.Headers.Add("Authorization", credentials);
                request.Headers.Add("accept", "application/json");
                response = await client.PutAsync("https://xmltestapi.propay.com/ProPayAPI/signup", content);
                responseBody = await response.Content.ReadAsStringAsync();
                objEventLog.AddLog("Merchant Onboarding Request Sent", portalSettings, userId,
                    response.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
                Console.WriteLine(responseBody);

            }
            catch (HttpRequestException ex)
            {
                result.Succeeded = false;
                result.Status = ex.Message;
                objEventLog.AddLog("Merchant Onboarding Error!", portalSettings, userId, response.ToString(),
                    EventLogController.EventLogType.ADMIN_ALERT);
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", ex.Message);
            }

            return response.Content.ToString();
        }
    }
public static string GetCredentials()
    {
        GatewaySetting_ProPay gatewaySettings = new GatewaySetting_ProPay();
        var billerAccountId = "mycreds";
        var authToken = "mycreds";
        var encodedCredentials =
            Convert.ToBase64String(Encoding.Default.GetBytes(billerAccountId + ":" + authToken));
        var credentials = string.Format("Basic {0}", encodedCredentials);
        return credentials;
    } 

When I wire this method up to a click event, an HTTP 302 response is received and nothing is sent to the API. 当我将此方法关联到click事件时,将收到HTTP 302响应,并且没有任何内容发送到API。 What modifications are needed to ensure proper transmission? 需要进行哪些修改以确保正确传输?

Update I still receive the following response: 更新我仍然收到以下响应:

Error code 302 was received from server response.

This is despite implementing the AllowAutoRedirect property and setting it to true. 尽管实现了AllowAutoRedirect属性并将其设置为true。 Here's the LoggingHandler class I've written: 这是我编写的LoggingHandler类:

public LoggingHandler(HttpMessageHandler innerHandler) : base(innerHandler)
    {

    }
    protected async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken, HttpClientHandler handler)
    {
        Console.WriteLine("Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();
        handler.AllowAutoRedirect = true;
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);


        Console.WriteLine("Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }

Is this the proper way to implement HttpClientHandler and associated properties? 这是实现HttpClientHandler和相关属性的正确方法吗?

确保HttpClientHandler实例的AllowAutoRedirect属性设置为true,并且由HttpClient使用。

After implementing trace logs for System.Net.Http and related namespaces, the logs stated that the connection was forcibly closed. 在为System.Net.Http和相关名称空间实现跟踪日志后,日志说明该连接被强制关闭。 After further research, it turns out the .NET Framework 4.5 is not compatible with more modern Transport Layer Security (TLS) versions. 经过进一步研究,结果发现.NET Framework 4.5与更现代的传输层安全性(TLS)版本不兼容。 As such, the approach of calling the API from our DNN application had to be jettisoned because the source code we're extending targets .NET Framework version 4.5. 因此,必须放弃从DNN应用程序调用API的方法,因为我们要扩展的源代码针对.NET Framework 4.5版。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM