我試圖通過HTTP客戶端訪問API的Post方法並傳遞AuthToken。當我嘗試訪問post man時,我能夠得到響應,但是當我用C#運行時,得到了StatusCode:401,ReasonPhrase:'未授權'錯誤。我與我的代碼一起共享郵遞員的請求和響應屏幕。任何人都可以讓我知道我在代碼中所犯的錯誤以及如何解決問題。下面StatusCode:401,ReasonPhrase:使用C#通過HTTPClient調用Post方法時顯示'未授權'
Postman Request Header and Response 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());
}
安裝* Fiddler *,比較郵差到C#請求和播放差異。 –
找到問題的最佳方式是使用wireshark或fiddler之類的嗅探器。使用post man與http客戶端比較http頭。從初始請求的第一個標題開始,使其看起來完全像郵遞員標題。 – jdweng
絕對在Postman上寫出代碼之前試用它。 – Rafael