简体   繁体   中英

How to Redirect with POST method and headers

API description here I need to redirect to an API using c#, but I need to use POST method and add some headers to it. I know Redirect function uses GET method and you can use the POST method by html form but with html form I can't add headers. So is ajax call the only way to do this? And if so, can you give me a sample code on how to achieve this on codebehind c#?

I tried something like that but I keep getting an error of input string not in correct format for the ajax call string.

if (Request["code"] != null)
        {
            string AuthCode = Request["code"];
            var byteArray = Encoding.ASCII.GetBytes($"{clientID}:{clientSecret}");
            var clientAuthHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();

            string url = "https://sandbox-oauth.hellenicbank.com/token/exchange?grant_type=authorization_code&redirect_uri=" + redirectUri + "&code=" + AuthCode;
            string ajaxCall = "$.ajax({type: 'POST', url: '" + url + "', " +
            "contentType: 'application/json; charset=utf-8', " +
            "data: '', " +
            "dataType: 'json', " +
            "beforeSend: function(xhr) {xhr.setRequestHeader('Authorization', '" + clientAuthHeader.ToString() + "');}, " +
            "});";

            StringBuilder s = new StringBuilder();
            s.Append("<html>");
            s.Append("<head>");
            s.AppendFormat("<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>");
            s.Append("</head>");
            s.Append("<body>");
            s.Append("<script>");
            s.AppendFormat(ajaxCall);
            s.Append("</script></form></body></html>");
            response.Write(s.ToString());
            response.End();
            return;
        }

Edit: I tried the POST request in c# with the following code. Apparently, I must be doing something wrong cause I'm not getting an exception nor a json.

public async Task<JObject> ExhcangeToken(string header, string url)
    {
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.Headers.Add("Authorization", "Basic " + header);
        
        try
        {
            WebResponse response = await request.GetResponseAsync();
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string responseContent = reader.ReadToEnd();
                JObject adResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(responseContent);
                return adResponse;
            }
        }
        catch (WebException webException)
        {
            Json = webException.ToString();
            if (webException.Response != null)
            {
                using (StreamReader reader = new StreamReader(webException.Response.GetResponseStream()))
                {
                    string responseContent = reader.ReadToEnd();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(responseContent); ;
                }
            }
        }

        return null;
    }

EDIT: Ok, so i changed the request code and tried with RestSharp this time and finally, I got a response. The problem is that i get a 404 not found error. This is the new code:

if (Request["code"] != null)
        {
            string AuthCode = Request["code"];
            var byteArray = Encoding.ASCII.GetBytes($"{clientID}:{clientSecret}");
            var clientAuthHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            string url = "https://sandbox-oauth.hellenicbank.com/token/exchange?grant_type=authorization_code&redirect_uri=" + redirectUri + "&code=" + AuthCode;
            var client = new RestClient(url);
            var request = new RestRequest();

            request.Method = Method.POST;
            request.AddHeader("Authorization", clientAuthHeader.ToString());
            request.Parameters.Clear();

            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            var queryResult = client.Execute(request);
            return;
        }

I tried calling the API from https://reqbin.com/ with the same url im using in my code and it works fine. So, im guessing the problem must be with the authentication header im using. In the API description asks for [Headers] Authorization: Basic Base64Encode(YOUR_CLIENT_ID:YOUR_CLIENT_SECRET). Am I adding this header the correct way?

This is the JSON response im getting

EDIT: Solved it. I made the authentication like this:

client.Authenticator = new HttpBasicAuthenticator(clientID, clientSecret);

It worked. I finally got the access token. Thanks so much for your help.

Worked by using RestSharp

Final code:

if (Request["code"] != null)
        {
            string AuthCode = Request["code"];

            string url = "https://sandbox-oauth.hellenicbank.com/token/exchange?grant_type=authorization_code&redirect_uri=" + redirectUri + "&code=" + AuthCode;
            var client = new RestClient(url);
            var request = new RestRequest();

            request.Method = Method.POST;
            client.Authenticator = new HttpBasicAuthenticator(clientID, clientSecret);
            request.Parameters.Clear();

            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            var queryResult = client.Execute(request);
            return;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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