StatusCode:401,ReasonPhrase:' Unauthorized'使用C#通过HTTPClient调用Post方法时显示

时间:2017-08-11 16:37:14

标签: c# api httpclient postman dotnet-httpclient

我正在尝试通过HTTP客户端访问API的Post方法并传递AuthToken。当我尝试访问post man时,我能够得到响应,但是当我在C#中运行时,我得到了StatusCode:401,ReasonPhrase:' Unauthorized'错误。我正在分享Postman的请求和响应屏幕以及我的代码。任何人都可以让我知道我在代码中所犯的错误以及如何解决问题。

Postman Request Header and Response Body

Postman Request Body

下面是我的C#代码。

    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());
        }

0 个答案:

没有答案