Search code examples
c#postmandotnet-httpclient

StatusCode: 401, ReasonPhrase: 'Unauthorized' gets displayed when calling a Post Method through HTTPClient using C#


I am trying to access an API's Post method through HTTP Client and passing the AuthToken. When I tried to access in post man I am able to get the response, but when I ran in C#, I got StatusCode: 401, ReasonPhrase: 'Unauthorized' error. I am sharing the request and Response screens of Postman along with my code. can anyone let me know the mistake which I did in the code and how to solve the issue.

Postman Request Header and Response Body

Postman Request Body

Below is my C# code:

public class PostEmpData
{
    public string cExternalGUID = "10134", 
    cEmployeeID = "10134", cLastName = "Anderson", cFirstName = "Derek", cAccessGroup = "", cActive = "A";
    public int nCardNumber = 10134, nPayMethod = 2;
    public string[] cGroupsList = new string[0] { };
    public DateTime dHireDate = DateTime.Parse("1999 / 11 / 03"), dTermDate = DateTime.Parse("01 / 01 / 0001"), dRateEffectiveDate = DateTime.Parse("2017 - 07 - 15");
    public decimal nPayRate = 1500;
}

    public class PostEmployeeClass
{
    public int _interfaceID { get; set; }
    public int _errorCode { get; set; }
    public string _errorDescription { get; set; }
    public List<EmpPostResponse> respList;
}

public class EmpPostResponse
{
    public string RetKey { get; set; }
    public int ErrorCode { get; set; }
    public string Description { get; set; }
    public string Success { get; set; }
    public string SecondaryList { get; set; }
}


     static async Task<List<EmpPostResponse>> CallPostEmployeeAsync(object postdata)
    {
        Console.WriteLine("Post Employee Process Started");
        PostEmployeeClass authclass = null;
        List<EmpPostResponse> data = null;
        HttpResponseMessage response = await client.PostAsJsonAsync("xxxxxxV2/api/ED907F98-9132-4C7D-B4D4-7648A2577F6D/Integration/employees", postdata);
        response.EnsureSuccessStatusCode();
        
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("success");
            authclass = await response.Content.ReadAsAsync<PostEmployeeClass>();

            data = authclass.respList;
        }
        else
            Console.WriteLine("fail:" + response.StatusCode.ToString());

        return data;
    }
    static void Main(string[] args)
    {
        Console.WriteLine("Starting the Process");
        RunAsync().Wait();
    }
    static async Task RunAsync()
    {
        PostEmpData objPost = new PostEmpData();
        client.BaseAddress = new Uri("https://xxxx.xxxxx.com/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        try
        {
            string AuthToken="XXXXXXXXXXXXX";
            client.DefaultRequestHeaders.Add("AuthToken",  AuthToken);
            
            Console.WriteLine(AuthToken);
           
            var postdata = CallPostEmployeeAsync(objPost);
             
        }catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

Solution

  • I've reviewed your code and there are a few things that I noticed.

    One thing that is not going to work: PostEmpData will serialize into an empty object as it contains no properties. So the body will be something like: {}. You will need to add properties to the class:

    public class PostEmpData
    {
        public string cExternalGUID { get; set; } = "10134";
        public string cEmployeeID { get; set; } = "10134";
        public string cLastName { get; set; } = "Anderson";
        public string cFirstName { get; set; } = "Derek";
        public string cAccessGroup { get; set; } = "";
        public string cActive { get; set; } = "A";
        public int nCardNumber { get; set; } = 10134;
        public int nPayMethod { get; set; } = 2;
        public string[] cGroupsList  { get; set; }= new string[0] { };
        public DateTime dHireDate  { get; set; }= DateTime.Parse("1999 / 11 / 03");
        public DateTime dTermDate  { get; set; }= DateTime.Parse("01 / 01 / 0001");
        public DateTime dRateEffectiveDate  { get; set; }= DateTime.Parse("2017 - 07 - 15");
        public decimal nPayRate  { get; set; }= 1500;
    }
    

    There is a good chance that this causes the unauthorized response. And that it may have nothing to do with the token.

    And there is also another difference compared to the Postman request. With Postman you send an array of object [{}], but with code you send one object. So you may have to post a list of PostEmpData.