I'm going to implement Learn Upon API into my .NET MVC application, they gave cURL and I have to convert these cURL URL into the web request in C# for getting or sending data to the third party Learn Upon API server thing is that Listing API, Delete API was working fine but Create & Update API always returns The remote server returned an error: (404) Not Found.
cURL sample given by Learn Upon:
curl -X POST -H "Content-Type: application/json" --user 988d4f1313f881e5ac6bfdfc7f54244aab : 905a12r3a0c -d '{"User": {"last_name" : "Upon",
"first_name" : "Learn", "email" : "learnuponapi@samplelearningco.com", "password" : "password1", "language" : "en", "membership_type" : "Member"
}}' https://yourdomain.learnupon.com/api/v1/users
As per above cURL, I have written below web request call for API calls, and this pattern worked in Listing/Delete API.
- POST Model:
{
"first_name": "Krishna",
"last_name": "Patel",
"email": "krishna.patel@test.com",
"password": "1234567890",
"language": "en",
"membership_type": "Member",
"username":"krishna.patel"
}
- Create API Code:
[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 Returns: { "Message": "The remote server returned an error: (404) Not Found." }
Note: Above message comes from the exception catch block, every time exception occurs and return 404 response.