0

I'm trying to send an HTTP request from .NET Core 3.1 REST API to another API but below Exception keep appeared Although I'm already added the Authentication Key :

The request was missing an Authentication Key. Please, refer to section "Authentication"

here is my code :

public class AppService
    {


        private readonly IHttpClientFactory _clientFactory;
        string key = "key=llllll ......";
        string webAPIKey = "......";
        string Id = "......";

        public AppService(IHttpClientFactory clientFactory) {
            _clientFactory = clientFactory;
           
        }

public async Task<string> sendBroadCastNotification()
        {
            Data _data = new Data();
            _data.title = "test data Ttile";
            _data.detail = "test data detail";
            Notification _notification = new Notification();
            _notification.title = "test notification Ttile";
            _notification.body = "test notification body";

            MyNotification NotifcationData = new MyNotification {
            data=_data,
            notification=_notification,
            to= "/topics/all"
            };

            try {
           

            var client = _clientFactory.CreateClient();

               

            client.DefaultRequestHeaders.Add("project_id", Id );
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);


                StringContent bodyOfRequest = new StringContent(System.Text.Json.JsonSerializer.Serialize(NotifcationData ), Encoding.UTF8, "application/json");

            using var httpResponse =
          await client.PostAsync("https://.......", bodyOfRequest);

                var result = httpResponse.Content.ReadAsStringAsync().Result;

                return result;
            }
            catch (Exception ex)
            {
                throw new System.ArgumentException(ex.Message.ToString(), "original");

            }
            //return null;

        }


}

Abdulaziz
  • 654
  • 3
  • 12
  • 37
  • What format does the API expect the Authorization header to be in? What you currently have set is doing this: `Authorization: Authorization mykey123`. By adding the extra ctor param you are adding a scheme, which is added as a prefix. Is that what you expect? – Simon C Aug 28 '20 at 22:17
  • @SimonC I wanna add Authorization: 'key=...mykey' i in the header such as PostMan request – Abdulaziz Aug 29 '20 at 01:51
  • @SimonC you can check my update – Abdulaziz Aug 29 '20 at 01:54

1 Answers1

0

I found the answer here in this link:

I add the key by using the below line:

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", key);

the below way that I was trying to add the authorization header wasn't understandable as an authorization header :

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);

Abdulaziz
  • 654
  • 3
  • 12
  • 37