0

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.

  1. POST Model:
{
  "first_name": "Krishna",
  "last_name": "Patel",
  "email": "krishna.patel@test.com",
  "password": "1234567890",
  "language": "en",
  "membership_type": "Member",
  "username":"krishna.patel"
}
  1. 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.

  • "message comes from the exception catch block" Are you really sure about that? That exception should return a HTTP 500 status. the 404 seems to indicate a problem with your routing, if no appropriate route for your POST can be found, a 404 will occur. – oerkelens May 22 '19 at 07:00
  • @oerkelens, Yes I have added my code into try & catch block thing is that others 2 cURL working fine with same code format but only Insert & Update cURL return **"The remote server returned an error: (404) Not Found."**, If any problem with routing then it will also be returned in Listing & Delete cURL – Krishnakumar Patel May 22 '19 at 09:10

1 Answers1

1

Are you sending any data in the POST request body?

It looks to me, as someone with very little C# experience, as if you're sending the mdlUser data as a HTTP Request Header (called data), and not sending anything in the POST body. There are a few examples of making a POST request in this question: How to make HTTP POST web request

That's likely to be the 404 problem (or, at least, the first one!). The exception you're catching is a legitimate exception (4xx is mostly considered an non-normal state). If you want to capture a 404 (which can be a legitimate response for the LearnUpon API when, for example, checking if a user exists in your portal), look at this question: How can I catch a 404?

Finally, feel free to reach out to your LearnUpon support team. We might not have all the answers a developer needs, but we can normally point you in the right direction.

Disclaimer: I work with LearnUpon.

cgarvey
  • 11
  • 2