我正在为我的桌面应用程序使用 API。该应用程序运行在 dot.net 框架 3.5.
我有一个可以完美运行的 API,但是当我从桌面应用程序调用 API 时,出现错误:
“远程服务器返回错误:(404)”
但是我的API运行没有问题。我有两个参数,将在 URL 中传递。
这是我的代码:
string url = "http://localhost:58167/api/Project/";
string data = "65354/19216882";
string response;
WebClient client = new WebClient();
{
client.Encoding = Encoding.UTF8;
response = client.downloadstring(url, "POST", data);
}
我该如何解决这个问题?
编辑: 这是说明 API 外观的代码:
// GET api/Project
public string GetProjects(string key, string IP)
{
string sql = "";
string en = "";
if (IP == "19216")
sql = "garbage1";
if (IP == "19882")
sql = " garbage2";
if (IP == "181249")
sql = " garbage3";
if (IP == "85206")
sql = " garbage4";
if (IP == "87249")
sql = " garbage5";
en = CryptorEngine.Encrypt(sql, key);
return en;
}
更新解决的代码:
string url = "http://localhost:58167/api/Project/";
string data = "65354/19216882";
string response;
WebClient client = new WebClient();
{
client.Encoding = Encoding.UTF8;
response = client.downloadstring(url, "POST", data);
}
尝试将属性路由添加到您的 API
Route[("~/api/Project/{key}/{ip}")]
public string GetProjects(string key, string IP)
你的代码
string url = "http://localhost:58167/api/Project/65354/19216882";
string response;
WebClient client = new WebClient();
{
client.Encoding = Encoding.UTF8;
response = client.UploadString(url, "GET");
}
如果您无法控制 api
你可以使用现有的动作
Route[("~/api/Project")]
public string GetProjects(string key, string IP)
代码
string url = "http://localhost:58167/api/Project?key=65354&IP=19216882";
string response;
WebClient client = new WebClient();
{
client.Encoding = Encoding.UTF8;
response = client.UploadString(url, "GET");
}
如果您仍然需要使用 POST,则必须修复 acion
public class ViewModel
{
public string Key {get; set;}
public string IP {get; set;}
}
Route[("~/api/Project")]
public string GetProjects([FromBody]ViewModel model)
谢谢大家。我得到了解决,并更新了有问题的更新代码。只需将 uploadstring 更改为 downloadstring 。和宾果……它有效。 –
更新解决的代码:
string url = "http://localhost:58167/api/Project/";
string data = "65354/19216882";
string response;
WebClient client = new WebClient();
{
client.Encoding = Encoding.UTF8;
response = client.downloadstring(url, "POST", data);
}