Home > Software design >  C# REST Api always return 401 status code when i am calling API by HttpClient
C# REST Api always return 401 status code when i am calling API by HttpClient

Time:08-10

I am working with Nasdaq Fund Network Data Service first time. i am calling their one of the API where passing user id,pwd and access key but always getting 401 status code. i am not able to figure out what is wrong in my http call. please some one have a look at the code and tell me where i made the mistake for which i am getting 401 status code instead of right response.

here is my sample code where i could not share actual credentials and access key. giving the code

string url = "sample url";
Uri u = new Uri(url);

string username = "test1";
string password = "test2";
string accessKey = "myaccesskey";

var payload = new Dictionary<string, string>
{
  {"username", username},
  {"password", password},
  { "accessKey", accessKey}
};

string strPayload = JsonConvert.SerializeObject(payload);
//HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/json");
HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/x-www-form-urlencoded");

var response = string.Empty;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
    HttpRequestMessage request = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = u,
        Content = c
    };

    var result = client.SendAsync(request).Result;
    if (result.IsSuccessStatusCode)
    {
        response = result.StatusCode.ToString();
    }
}

This Error i am getting

{StatusCode: 401, ReasonPhrase: 'Check Username/Password or Access Key', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache X-Frame-Options: SAMEORIGIN Cache-Control: no-cache Date: Wed, 10 Aug 2022 11:55:36 GMT Content-Length: 0
Expires: -1 }}

CodePudding user response:

It could be the way you authenticate to the service. One way to confirm is testing by Postman. Testing for it works?

CodePudding user response:

You should add the access token to your Header and not to the Content.

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

CodePudding user response:

We would need some more information to be honest. What is the API expecting? It seems like it's expecting FormData and you're sending a JSON string as StringContent.

Try the following:

var url = "https://nfn.nasdaq.com/servicecall/tempsession";
var username = new StringContent("test1");
var password = new StringContent("test2");
var accessKey = new StringContent("myaccesskey");

var formData = new MultipartFormDataContent
                {
                    { username, "username" },
                    { password, "password" },
                    { accessKey, "accessKey" }
                };

using (var client = new HttpClient())
{
    var response = await client.PostAsync(url, formData);

    response.EnsureSuccessStatusCode();
}

CodePudding user response:

Try the following in order to extract the JWT token you receive as a response.

    var url = "https://nfn.nasdaq.com/servicecall/tempsession";

    var formDataDictionary = new Dictionary<string, string>
    {
        { "username", "test1"},
        { "password", "test2"},
        { "accessKey", "myaccesskey"}
    };

    var formData = new FormUrlEncodedContent(formDataDictionary);

    using (var client = new HttpClient())
    {
        var response = await client.PostAsync(url, formData);

        response.EnsureSuccessStatusCode();

        var result = await response.Content.ReadAsStringAsync();

        var responseBody = JObject.Parse(result);
        var accessToken = responseBody["data']"].Value<string>();
    }
  • Related