отправить JSON Объект в ASP. NET - PullRequest
0 голосов
/ 11 апреля 2020

я пытаюсь отправить объект в формате JSON, но метод всегда получает нулевой объект

здесь ОШИБКА:

Server Error in '/' Application.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Source Error: 


Line 15:             context = ApplicationDbContext.Create();
Line 16:             context.Users.Add(user);
Line 17:             if (context.SaveChanges() == 0)
Line 18:             {
Line 19:                 context.Dispose();

Source File: D:\Education\Git\Online-Store-Platform-API\OnlineStorePlatform\OnlineStorePlatform\DBContext\UserContext.cs    Line: 17 

и это мой код:

public class AccountController : Controller
    {
        //public UserDTO user;
        public UserContext myContext;
        // GET: Account
        public ActionResult Index()
        {
            return View();
        }
        //[HttpPost]
        public ActionResult Register([FromBody]UserDTO user)
        {
            //user = new UserDTO(email, password, userName);
            myContext = new UserContext();
            if (myContext.addUser(new User(user)) == null) return Content("ERROR");
            return Content("Created Successfully");
        }
    }

когда я отправляю объект UserDTO, всегда получаю нулевой

мой запрос:

JSON request

UseDTO класс :

public class UserDTO
    {
        public String email, userName, password;
        public UserDTO(String email, String password, String userName)
        {
            this.email = email;
            this.password = password;
            this.userName = userName;
        }
        public UserDTO() { }
    }

при попытке отладки я получил нулевой объект

debugging img

Ответы [ 3 ]

0 голосов
/ 11 апреля 2020

Преобразование электронной почты, имени пользователя и пароля в собственность.

publi c string Email {get; набор;}

0 голосов
/ 12 апреля 2020

Хорошо, я нашел решение своей проблемы .. проблема в том, что я наследую от класса Controller, но я должен наследовать от ApiController.

public class AccountController : Controller
    {
        ........
    }

после этого все заработало .. спасибо всем

0 голосов
/ 11 апреля 2020
public class AccountController : Controller
{
    public UserContext myContext;

    public AccountController () : this(new UserContext()) {}

    public AccountController (UserContext _myContext) 
    {
       myContext = _myContext;
    }


    // GET: Account
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Register(UserDTO user)
    {
        if (ModelState.IsValid) {
           myContext.Add(User);
          //ToDo: Redirect or many options
        }
        return View(user);
    }
}

Редактировать:

Это важно

public class UserDTO
{
    public String email { get; set; }
    public String userName  { get; set; }
    public String password  { get; set; }
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...