【发布时间】:2020-05-12 02:50:58
【问题描述】:
我有一个已知的有效 API。当我使用下面的代码调用它时,它作为 NULL 值传入。
代码:
public bool Serial_Key_Exist(WBG_Serial_Key Serial_Key)
{
bool exists = false;
string verification = string.Empty;
string uri = _EndPoint + "api/WhiteBoXGaming/Post_SerialKeyExist";
var ujson = JsonConvert.SerializeObject(Serial_Key);
var request = WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = ujson.Length;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(ujson);
}
using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
verification = reader.ReadToEnd();
}
if (verification == "true") { exists = true; }
return exists;
}
我对我的 api 的调用有问题吗?这是课程:
[System.Serializable]
public class WBG_Serial_Key
{
public string Email { get; set; }
public string Product { get; set; }
public string Serial_Key { get; set; }
}
我做错了吗?有人有建议吗?
更新: 我按照建议调整了代码仍然无法正常工作:
public bool Serial_Key_Exist(string serial)
{
bool rsp = false;
WBG_Serial_Key Serial_Key = new WBG_Serial_Key();
Serial_Key.Email = "";
Serial_Key.Product = _Product;
Serial_Key.Serial_Key = serial;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_EndPoint);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("api/WhiteBoXGaming/Post_SerialKeyExist", rsp).Result;
if(response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<bool>().Result;
}
//default failed - Prevent duplicate keys
return true;
}
}
这里是 API 代码:
[Route("api/WhiteBoXGaming/Post_SerialKeyExist")]
[HttpPost]
public bool SerialKeyExist([FromBody]WBG_Serial_Key Key)
{
bool Exist = false;
Exist = _DataHelper.Serial_Key_Exist(Key.Serial_Key, Key.Product);
return Exist;
}
更新: 现在我有一个新问题,它现在一直死锁。无论如何要在不使用异步的情况下获得返回结果?
【问题讨论】:
-
也许您的 API 代码错了?我看到很多人试图用
ApiMethod(string myJsonBody)之类的东西来接受 JSON 服务器端,这当然是行不通的,然后他们想知道为什么会得到null。 -
另外,
WebRequest是 not recommended to be used,请改用HttpClient -
如果您认为您的想法可行,请发布示例代码