web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

How to pass bearer token in System.Net.WebHeaderCollection.Add

(0) ShareShare
ReportReport
Posted on by 184

Hello All,

I am getting 400 Bad request error when I am trying to call an API.

Can someone please tell me if I  am passing the token in a proper way.? Because I feel that the way I am passing token is not correct

Token_5F00_Header.PNG

I have the same question (0)
  • D365_Wibes Profile Picture
    184 on at

    {"token_type":"Bearer","expires_in":3599,"ext_expires_in":3599,"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGxWMFRPSSJ9.eyJhdWQiOiJiYzY3NDc0ZS02MTJiLTRkN2YtYjc1YS1hYzU0ZDQ1ZjE0M2EiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vMjRmOWQ3NTYtYmYwYy00M2U5LWFkNWUtMjA3M2FlMmQ2Njk4L3YyLjAiLCJpYXQiOjE2NjMwODA0OTUsIm5iZiI6MTY2MzA4MDQ5NSwiZXhwIjoxNjYzMDg0Mzk1LCJhaW8iOiJFMlpnWUtqWjViSGwrSUtIaDcwV0wxck9MblVqREFBPSIsImF6cCI6ImJiMDMwOWE0LTc4ZWEtNGI0ZS1hZGRiLWVhM2YzMzQyOGE5ZCIsImF6cGFjciI6IjEiLCJyaCI6IjAuQVNJQVZ0ZjVKQXlfNlVPdFhpQnpyaTFtbUU1SFo3d3JZWDlOdDFxc1ZOUmZGRG9qQUFBLiIsInRpZCI6IjI0ZjlkNzU2LWJmMGMtNDNlOS1hZDVlLTIwNzNhZTJkNjY5OCIsInV0aSI6Ikd0VFR4bll2TWt1U3RMeEN6Ynh2QWciLCJ2ZXIiOiIyLjAifQ.NyipbhdXlaiLaOTwW7as6FnycBHfe_NVbc4P_1TOQtp5cWnTUFS1z-HcUNauicH1gfpN_z5TS1_ZvHmcyNQkV1z0eNIHQRoul0FkucM8sfijcRmQa6868LMhhDKDJPoZqKBaTluJ6s3TIhxztALDjxOoSEjrhQulAIGTGjtyEcny6up0jfOy5xXb0ZYJasgG58td6QLmCbLxFpy25W_5L_3ahnkkXaWAXAfb8zd5VBrvqIr3BHMyX5lsmMpE1Uz3V38dtSlcf3s19eUxoF_G3VhpUaIIgwfrvxlBQaF6m0JT50KDfrzTNqPOTIRWibUEAdv-s4_AvFjFqo0oozmAIw"}

    Just to add that I am passing the whole string as token to the header via WTL_6DeeAPITokenService::getToken()

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    You should have a space between "Bearer" and the token. You don't seem to have that, unless your getToken() method returns a string beginning with a space.

    By the way, what is the purpose of your clrObj variable? It looks useless to me.

    And forget to dispose resources.

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    What you should out to the header is the value of "access_token", not the whole JSON object.

  • D365_Wibes Profile Picture
    184 on at

    HI Martin,

    Thanks a lot for the response.

    Could you tell me how to get the access_token from JSON object and pass it to the header?

  • D365_Wibes Profile Picture
    184 on at

    Also martin please tell me how to dispose the resources

  • D365_Wibes Profile Picture
    184 on at

    System.Net.HttpWebRequest       request;
    System.Net.HttpWebResponse      response;
    CLRObject                       clrObj;
    System.Exception                ex;
    System.Net.WebHeaderCollection  httpHeader;
    System.IO.Stream                requestStream, responseStream;
    System.IO.StreamWriter          streamWriter;
    try
    {
        httpHeader = new System.Net.WebHeaderCollection();
        new InteropPermission(InteropKind::ClrInterop).assert();
        request = System.Net.WebRequest::Create("https://API URL");
        //request = clrObj;
        // adding headers
       
        httpHeader.Add("Authorization", "acess_token"   WTL_6DeeAPITokenSerice::getToken());
        httpHeader.Add("requestid", "23556667772");
        httpHeader.Add("sourcenode", "ERP");
        httpHeader.Add("requesttimestamp", "2022-09-12");
        request.set_Headers(httpHeader);
        request.Method = "POST";
        request.ContentType = "application/json";
        requestStream = request.GetRequestStream();
        streamWriter = new System.IO.StreamWriter(request.GetRequestStream());
        System.Byte[] postBytes;
        System.Text.Encoding encoding = System.Text.Encoding::get_ASCII();
        str sJSON = WTL_6DJSONserializer::serializeJSON(_profileGUID,_transactionID,strFmt("%1",_amount),
                                                               _paymentMode,_accountID,_currencyCode,
                                                               _customerName,strFmt("%1",_amountPaid),
                                                               _externalID,_cardHolderName,_modelValue,_modelKey,
                                                               _paymentGWtoken,_comment,_authToken,_orderType,
                                                               _id,_value,_contactNumber);
        postBytes = encoding.GetBytes(sJSON);
        streamWriter.Write(postBytes); // writing JSON
        streamWriter.Flush();
        streamWriter.Close();
        response = request.GetResponse();
        System.IO.StreamReader streamRead = new System.IO.StreamReader(response.GetResponseStream());
        info(streamRead.ReadToEnd());
    }
    catch (Exception::CLRError)
    {
        throw error(AifUtil::getClrErrorMessage());
    }

    I have changed the removed the CLRobject and below is my modified code.

    Please can you tell me what am I doing wrong:

  • D365_Wibes Profile Picture
    184 on at

    I am getting error at line# 37  (response = request.GetResponse())  

    Error   -    "400 Bad Request"

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    There are several ways how you can deserialize JSON. A common way is creating a class with the same structure as the JSON (if you do parsing in C#, you can utilize "Paste JSON as classes"), deserializing the string to this object and accessing object properties by name.

    If you don't see it worth the effort, you can utilize Newtonsoft.Json to deserilize the string to JObject and access object members by methods like SelectToken(). For example:

    JObject jObject = JObject.Parse(json);
    jObject.SelectToken("$.access_token");

  • D365_Wibes Profile Picture
    184 on at

    Do I need to write the above code in C#?

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    Before doing anything else with your code, such as adding disposal, let me throw away unused variables, use a better way to access the exception and move variable declarations:

    using System.Net;
    using System.IO;
    
    ...
    
    System.Exception ex;
    
    try
    {
    	WebHeaderCollection httpHeaders = new WebHeaderCollection();
    	httpHeaders.Add("Authorization", "acess_token"   WTL_6DeeAPITokenSerice::getToken());
    	httpHeaders.Add("requestid", "23556667772");
    	httpHeaders.Add("sourcenode", "ERP");
    	httpHeaders.Add("requesttimestamp", "2022-09-12");
    	
    	HttpWebRequest request = System.Net.WebRequest::Create("https://API URL");
    	
    	request.set_Headers(httpHeaders);
    	request.Method = "POST";
    	request.ContentType = "application/json";
    	
    	StreamWriter streamWriter = new StreamWriter(request.GetRequestStream());
    	
    	
    	
    	str sJSON = WTL_6DJSONserializer::serializeJSON(_profileGUID,_transactionID,strFmt("%1",_amount),
    														   _paymentMode,_accountID,_currencyCode,
    														   _customerName,strFmt("%1",_amountPaid),
    														   _externalID,_cardHolderName,_modelValue,_modelKey,
    														   _paymentGWtoken,_comment,_authToken,_orderType,
    														   _id,_value,_contactNumber);
    	System.Text.Encoding encoding = System.Text.Encoding::get_ASCII();
    	System.Byte[] postBytes = encoding.GetBytes(sJSON);
    	streamWriter.Write(postBytes); // writing JSON
    	streamWriter.Flush();
    	streamWriter.Close();
    	
    	System.Net.HttpWebResponse response = request.GetResponse();
    	StreamReader streamRead = new StreamReader(response.GetResponseStream());
    	info(streamRead.ReadToEnd());
    }
    catch (ex)
    {
    	throw error(ex.Message);
    }
    

    What you do with ASCII encoding looks strange to me; let me throw it away. Also, you now have a bug in the header - you replaced Bearer with acess_token, whicdh is wrong, and you forgot to add the space. Let me fix it too.

    using System.Net;
    using System.IO;
    
    ...
    
    System.Exception ex;
    
    try
    {
    	WebHeaderCollection httpHeaders = new WebHeaderCollection();
    	httpHeaders.Add("Authorization", "Bearer "   WTL_6DeeAPITokenSerice::getToken());
    	httpHeaders.Add("requestid", "23556667772");
    	httpHeaders.Add("sourcenode", "ERP");
    	httpHeaders.Add("requesttimestamp", "2022-09-12");
    	
    	HttpWebRequest request = System.Net.WebRequest::Create("https://API URL");
    	
    	request.Headers = httpHeaders;
    	request.Method = "POST";
    	request.ContentType = "application/json";
    	
    	StreamWriter streamWriter = new StreamWriter(request.GetRequestStream());
    	
    	str json = WTL_6DJSONserializer::serializeJSON(_profileGUID,_transactionID,strFmt("%1",_amount),
    														   _paymentMode,_accountID,_currencyCode,
    														   _customerName,strFmt("%1",_amountPaid),
    														   _externalID,_cardHolderName,_modelValue,_modelKey,
    														   _paymentGWtoken,_comment,_authToken,_orderType,
    														   _id,_value,_contactNumber);
    	streamWriter.Write(json); // writing JSON
    	streamWriter.Flush();
    	streamWriter.Close();
    	
    	System.Net.HttpWebResponse response = request.GetResponse();
    	StreamReader streamRead = new StreamReader(response.GetResponseStream());
    	info(streamRead.ReadToEnd());
    }
    catch (ex)
    {
    	throw error(ex.Message);
    }
    

    Your code calls Close(), which is good, but it does only everything completes successfully. If it doesn't, you keep the writer open. You can utilize the 'using' statement to do it in both cases. And let's do it with the response too.

    using System.Net;
    using System.IO;
    
    ...
    
    System.Exception ex;
    
    try
    {
    	WebHeaderCollection httpHeaders = new WebHeaderCollection();
    	httpHeaders.Add("Authorization", "Bearer "   WTL_6DeeAPITokenSerice::getToken());
    	httpHeaders.Add("requestid", "23556667772");
    	httpHeaders.Add("sourcenode", "ERP");
    	httpHeaders.Add("requesttimestamp", "2022-09-12");
    	
    	HttpWebRequest request = System.Net.WebRequest::Create("https://API URL");
    	
    	request.Headers = httpHeaders;
    	request.Method = "POST";
    	request.ContentType = "application/json";
    	
    	str json = WTL_6DJSONserializer::serializeJSON(
    		_profileGUID,
    		_transactionID,
    		strFmt("%1",_amount),
    		_paymentMode,
    		_accountID,
    		_currencyCode,
    		_customerName,
    		strFmt("%1",_amountPaid),
    		_externalID,
    		_cardHolderName,
    		_modelValue,
    		_modelKey,
    		_paymentGWtoken,
    		_comment,
    		_authToken,
    		_orderType,
    		_id,
    		_value,
    		_contactNumber);
    	
    	using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
    	{
    		streamWriter.Write(json); // writing JSON
    		
    		using (System.Net.HttpWebResponse response = request.GetResponse())
    		{
    			StreamReader streamRead = new StreamReader(response.GetResponseStream());
    			info(streamRead.ReadToEnd());
    		}
    	}
    }
    catch (ex)
    {
    	throw error(ex.Message);
    }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 660 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 549 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 307 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans