I've got my Models all annotated up with validation rules.
I've got a controller store method set up to create a new Model.
I've got JSON being parsed from the request body, after making a copy of the stream so that it's still accessible later.
I'm just trying to actually use those annotations now without having to do a whole bunch of... this:
if (!json.ContainsKey("name")) {
throw new Exception("Name is not set.");
}
if (!json["name"].GetType().Equals(typeof(String))) {
throw new Exception("Name is not a string");
}
string name = ((string) json["name"]).Trim();
if (name.Length == 0) {
throw new Exception("Name cannot be empty");
}
if (name.Length > 100) {
throw new Exception("Name must be less than 100 characters.");
}
I can't find anything that doesn't make a bunch of mindless assumptions. This, for example, makes no sense; why would I care anything about ModelState for an object that doesn't exist yet? Why would I, for that matter, care about the state of a Model at the point of entry on an update endpoint? Shouldn't it be fixed before it's even inserted into the database?
// POST: Movies/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("ID,Title,ReleaseDate,Genre,Price, Rating")] Movie movie)
{
if (ModelState.IsValid)
{
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(movie);
}
I've tried Newtonsoft's JSON.NET Schema and it introduces so many hardline and contradictory requirements (on top of being paid and closed source) that it's just painful to use. Please don't recommend that.
Movieobject and you can validate it before attempting to insert it into your database. The ModelState tells you whether the incoming object passed all the validation rules you set for it, or not. I'm not really sure I understand what your beef is.