4
我有C#代碼將JSON數據發送到web API,但我一直得到401(未授權)響應。下面的代碼應該根據this function正確發出POST請求,對嗎?我也嘗試了相同結果的小變化。ASP.NET將JSON數據發佈到帶有驗證標頭的HTTP API
這是發出請求的代碼:
public async Task Create()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://zrh.cloudsigma.com/api/2.0/");
var testVM = new CS_VM("test");
var auth = string.Format("{0}:{1}", "[email protected]", "password");
var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
HttpResponseMessage response = await client.PostAsJsonAsync("servers", testVM);
if (response.IsSuccessStatusCode)
{
var a = "ok";
}
else
{
var a = "fail";
}
}
}
,這是被作爲JSON類:
public class CS_VM
{
public CS_VM(string type)
{
if ("test" == type)
{
cpu = 1000;
mem = 536870912;
name = "testServer";
vcn_password = "testserver";
}
}
public string name { get; set; }
public int cpu { get; set; }
public int cores { get; set; }
public int mem { get; set; }
public string status { get; set; }
public Owner owner { get; set; }
public Uri resource_uri { get; set; }
public string uuid { get; set; }
public string vcn_password { get; set; }
}
請求頭:
Authorization: Basic bWFpbEBtYWlsLmNvbTpwYXNzd29yZA==
而響應標題:
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Cookie
X-REQUEST-ID: 2584e232-5bb2-48c0-a307-67e6c03258c0
Date: Sun, 19 Jul 2015 21:39:21 GMT
Server: cloudflare-nginx
WWW-Authenticate: Digest nonce="1437341961.55:6967:0fd0a6b2dcde8f45a5ae288c3b73ee12", realm="users", algorithm="MD5",opaque="b228739d1711b0ff025703aea82ee2a208faaaa7", qop="auth", stale="false", Basic Realm="users"
CF-RAY: 2089941a6935168e-ARN
401通常意味着身份驗證 - 我的猜測是您的用戶名/密碼正在被拒絕。嘗試共享整個響應標題,看看那裏是否有更具體的細節。 – Brian
您可以檢查傳出請求以確保標題正確發送嗎? – Whymarrh
@Whymarrh我將它們添加到問題中。這是我可以在發送之前調試'client'對象 – nest