Forum General

why am l getting 500 internal server error in web api test?

AustyAusty Member ✭✭✭

l have wrote a post api to create users

[HttpPost]
    public User CreateUser(User user)
    {
        //User jsonToObject = JsonConvert.DeserializeObject<User>(user.ToString());
        if (ModelState.IsValid)
        {
            db.users.Add(user);
            db.SaveChanges();
        }
        else                    
        {
            throw new Exception("The posted Model is not valid");
        }

      return user;

    }

when l test on postman using this json

{
"FirstName":"Test",
"LastName":"Test",
"Email":"[email protected]",
"Password":"Testerrr123"
}

l get 500 internal server error.Below is my model to give more insight

public class User
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }


    [NotMapped]
    [Compare("Password")]
    public string ConfirmPassword { get; set; }
    public int UserType { get; set; }
    public DateTime Date_Created { get; set; }
}

Apologies on asking this here but this is suppose to serve as my mobile app backend..thanks ahead.

Answers

  • GraverobberGraverobber Member ✭✭✭

    I think it would be a great idea to add you Stacktrace/Exception description of the backend here.
    Quick questions:

    • Is your Databsae already set up, opened and running when you try to Add the user.
    • Can you see if the request appears on the backend?
    • If yes does it contain the parameters as you sent it?
  • AustyAusty Member ✭✭✭

    @Graverobber Thanks for the help.

    1. Yes my database running. l am using azure data studio to connect to the database
    2. l placed a breakpoint on Modelstate and used postman to post a request to the endpoint. it doesnt contain the parameters as sent
      The error is saying the "FirstName field is required". its giving this error message for all the required field
  • GraverobberGraverobber Member ✭✭✭

    That's weird, do you set the Content-Type header to application/json when sending the request?

  • AustyAusty Member ✭✭✭

    @Graverobber Yes..l did

    l tried send a request from xamarin.forms using the code below.

    void OnRegisterClicked(object sender, EventArgs e)
    {
    //post user data to api;
    //
    User customer = new User {
    FirstName = fullName.Text,
    LastName = fullName.Text,
    Email = email.Text,
    Password = password.Text,
    ConfirmPassword = confirmPassword.Text,
    UserType = Int32.Parse(usertype.Text),
    Date_Created = DateTime.Now,
    };

            var httpClient = new HttpClient();
            var jsonUser = JsonConvert.SerializeObject(customer);
    
            HttpContent httpContent = new StringContent(jsonUser);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    
    
            httpClient.PostAsync("http://localhost:5000/Api/accounts", httpContent);
            DisplayAlert("Success", "Your account has been created", "Ok");
    
        }.
    

    it hits the endpoint and gives the same error

  • GraverobberGraverobber Member ✭✭✭

    Can you show us how you handle the request receiving on the server side?
    Also how the User object is created that is passed to the CreateUser method?

  • AustyAusty Member ✭✭✭

    @Graverobber if l understand then l believe l am handling the request on the server using the CreateUser method in the web api.

    l am posting the JSON from postman directly to the create user method. the create user method is suppose to just receive and insert object to db.

  • GraverobberGraverobber Member ✭✭✭
    edited January 31

    Hmm okay then I'm sorry but I think I can not help.
    From my understanding your server should have a route set up somewhere "http://localhost:5000/Api/accounts" that will receive the request object. This object should have a body, normally as a String.
    Then this string can be used in order to create an Instance of your User object something like JSON.ToObject<User>(bodyString). And this user you need to pass to the CreateUser method then.
    But it seems all of this is working differently with Azure soooo yeah I'm out of knowledge here :D

  • AustyAusty Member ✭✭✭

    @Graverobber Thanks again.. l think the point l am out of knowledge is the conversion from json object to user object.

    please check out my updated code on createuser method.

            [HttpPost]
                    public User CreateUser([FromBody]string jsonstring)
                    {
                        User user = JsonConvert.DeserializeObject<User>(jsonstring);
                        if (ModelState.IsValid)
                        {
                            db.users.Add(user);
                            db.SaveChanges();
                        }
                        else
                        {
                            throw new Exception("The posted Model is not valid");
                        }
    
                      return user;
    
                    }
    
  • GraverobberGraverobber Member ✭✭✭

    Is it working now with that changed code or still failing?
    What is the content of the jsonString parameter?

  • AustyAusty Member ✭✭✭
    edited January 31

    @Graverobber still throwing errors.

    l am posting this json to the endpoint
    {
    "email":"[email protected]","lastName":"bl","password":"testerrr123","confirmPassword":"testerrr123"
    }
    with content-type : application/json

    its saying 500 internal server error.

Sign In or Register to comment.