Search code examples
c#http-posttoken

How to add Token into HTTP Post method in c#?


hello guys this is my task method, it is http post method, now I want to add it Token like

httpWebRequest.Headers["Authorization"] = "Some_Token";

so, I am newbie and don't know how to do that, can someone help me?

            Task t = Task.Run(async () =>
            {
                string GetReferralsByPersonalIdNumberURL = "http://somehost/api/Referral/GetExistingClaimsByReferralNumber";
                GetExistingClaimsByReferralNumberClass cust = new GetExistingClaimsByReferralNumberClass() { referralNumber = ReferalNumFromMedicine, pharmacyID = PharmacyIDFromMedicine, };
                var json = _Serializer.Serialize(cust);
                var response = await Request(HttpMethod.Post, GetReferralsByPersonalIdNumberURL, json, new Dictionary<string, string>());

               //  Request.Headers["Authorization"] = "SomeToken"; 
                string responseText = await response.Content.ReadAsStringAsync();

                da = convertJsonStringToDataset(responseText);
                // List<YourCustomClassModel> serializedResult = _Serializer.Deserialize<List<YourCustomClassModel>>(responseText);

                //  Console.WriteLine(da.GetXml());
                // Console.ReadLine();

            });
            t.Wait();

And this is request method used in [webmethod]

static async Task<HttpResponseMessage> Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary<string, string> pHeaders)
        {
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = pMethod;
            httpRequestMessage.RequestUri = new Uri(pUrl);
            foreach (var head in pHeaders)
            {
                httpRequestMessage.Headers.Add(head.Key, head.Value);
            }
            switch (pMethod.Method)
            {
                case "POST":
                    HttpContent httpContent = new StringContent(pJsonContent, Encoding.UTF8, "application/json");
                    httpRequestMessage.Content = httpContent;
                    break;

            }

            return await _Client.SendAsync(httpRequestMessage);
        }

I think i have to change inside request method, and also i think i did it in another way, hope you guys will understand what i am to trying


Solution

  • Call Request like this

    var headers = new Dictionary<string, string> {
        { "Authorization", "SomeToken" }
    };
    
    var response = await Request(HttpMethod.Post, GetReferralsByPersonalIdNumberURL, json, headers);