我要在 .net MVC 应用程序中实现 Learn On API ,他们提供了cURL,我必须将这些cURL URL转换为C#中的Web请求。用于获取数据或向第三方发送数据的功能了解上市API,删除API正常工作,但创建和更新API始终返回远程服务器返回错误:(404)未找到。
学习者提供的cURL示例:
curl -X POST -H“ Content-Type:application / json” --user 988d4f1313f881e5ac6bfdfc7f54244aab:905a12r3a0c -d'{“ User”:{“ last_name”:“ Upon”, “ first_name”:“学习”,“电子邮件”:“ learnuponapi@samplelearningco.com”,“ password”:“ password1”,“ language”:“ en”,“ membership_type”:“会员” }}'https://yourdomain.learnupon.com/api/v1/users
按照上面的cURL,我已经在下面的Web请求调用中编写了API调用,这种模式在Listing / Delete API中起作用。
我需要帮助来解决此问题,谢谢高级。
{
"first_name": "Krishna",
"last_name": "Patel",
"email": "krishna.patel@c-metric.com",
"password": "1234567890",
"language": "en",
"membership_type": "Member",
"username":"krishna.patel"
}
[System.Web.Http.HttpPost]
public IHttpActionResult CreateUser(UserModel mdlUser)
{
string content = "";
try
{
if (ModelState.IsValid)
{
// target url given by Learn Upon, Unique for each account
string yourTarget = "https://{domain}/api/v1/users";
string josnUserModel = JsonConvert.SerializeObject(mdlUser);
josnUserModel = "{\"User\":" + josnUserModel + "}";
WebRequest yourWebRequest = WebRequest.Create(yourTarget);
yourWebRequest.Method = "POST";
// Establish credentials (if necessary)
CredentialCache yourCredentials = new CredentialCache();
yourCredentials.Add(new Uri(yourTarget), "Basic", new NetworkCredential(username, password));
// Set your credentials for your request
yourWebRequest.Credentials = yourCredentials;
// Add basic authentication headers (if necessary)
yourWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(String.Format("{0}:{1}", username, password))));
yourWebRequest.Headers.Add("data", josnUserModel);
WebResponse yourWebResponse = yourWebRequest.GetResponse();
string s = yourWebResponse.ToString();
// Get your response stream
using (var reponseStream = yourWebResponse.GetResponseStream())
{
// Build a reader to read your stream
using (var responseReader = new StreamReader(reponseStream, Encoding.UTF8))
{
// Get your result here
content = responseReader.ReadToEnd();
JObject json = JObject.Parse(content);
return Ok(json);
}
}
}
else
{
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
}
}
catch (Exception ex)
{
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
}
}
API返回: { “消息”:“远程服务器返回错误:(404)未找到。” }
注意:以上消息来自异常捕获块,每次发生异常并返回404响应。
答案 0 :(得分:0)
您是否在POST请求正文中发送任何数据?
在我看来,作为C#经验很少的人,好像您正在将mdlUser
数据作为HTTP请求标头(称为data
)发送,而不在POST中发送任何内容一样身体。在此问题中,有一些发出POST请求的示例:How to make HTTP POST web request
这很可能是404问题(或者至少是第一个问题!)。您捕获的异常是合法异常(通常将4xx视为非正常状态)。如果要捕获404(例如,当您检查门户中是否存在用户时,这可能是LearnUpon API的合法响应),请查看以下问题:How can I catch a 404?
最后,请随时与您的LearnUpon支持团队联系。我们可能没有开发人员所需的所有答案,但通常可以为您指明正确的方向。
免责声明:我与LearnUpon合作。