Skip to content

Feature/#252 valid modelstate #316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using JsonApiDotNetCore.Extensions;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Models;
using JsonApiDotNetCore.Services;
Expand Down Expand Up @@ -152,6 +153,7 @@ public virtual async Task<IActionResult> PostAsync([FromBody] T entity)

if (!_jsonApiContext.Options.AllowClientGeneratedIds && !string.IsNullOrEmpty(entity.StringId))
return Forbidden();
if (!ModelState.IsValid) return BadRequest(ModelState.ConvertToErrorCollection());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: return on newline

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haha no problem


entity = await _create.CreateAsync(entity);

Expand All @@ -164,6 +166,7 @@ public virtual async Task<IActionResult> PatchAsync(TId id, [FromBody] T entity)

if (entity == null)
return UnprocessableEntity();
if (!ModelState.IsValid) return BadRequest(ModelState.ConvertToErrorCollection());

var updatedEntity = await _update.UpdateAsync(id, entity);

Expand Down
23 changes: 23 additions & 0 deletions src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using JsonApiDotNetCore.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore.Internal;

namespace JsonApiDotNetCore.Extensions
{
public static class ModelStateExtensions
{
public static ErrorCollection ConvertToErrorCollection(this ModelStateDictionary modelState)
{
ErrorCollection errors = new ErrorCollection();
foreach (var entry in modelState)
{
if (!entry.Value.Errors.Any()) continue;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: continue on newline

foreach (var modelError in entry.Value.Errors)
{
errors.Errors.Add(new Error(400, entry.Key, modelError.ErrorMessage, modelError.Exception != null ? ErrorMeta.FromException(modelError.Exception) : null));
}
}
return errors;
}
}
}
2 changes: 1 addition & 1 deletion src/JsonApiDotNetCore/JsonApiDotNetCore.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>2.3.2</VersionPrefix>
<VersionPrefix>2.3.3</VersionPrefix>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wondering if this should be a major version bump. It could break existing apps if they have annotations but aren't currently checking them. We could release this as a patch version behind a feature flag (e.g. options.ValidateModelState) with a default disabled value. Then in the next major release enable it by default. What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could argue that if they have annotations already on their entities, then its already invalid and it's now being flagged. However, the feature flag route makes sense for a minor release :-D

Made the changes

<TargetFrameworks>$(NetStandardVersion)</TargetFrameworks>
<AssemblyName>JsonApiDotNetCore</AssemblyName>
<PackageId>JsonApiDotNetCore</PackageId>
Expand Down
62 changes: 62 additions & 0 deletions test/UnitTests/Controllers/BaseJsonApiController_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
using Moq;
using Xunit;
using System.Threading.Tasks;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace UnitTests
{
Expand Down Expand Up @@ -153,6 +156,25 @@ public async Task PatchAsync_Calls_Service()
VerifyApplyContext();
}

[Fact]
public async Task PatchAsync_ModelStateInvalid()
{
// arrange
const int id = 0;
var resource = new Resource();
var serviceMock = new Mock<IUpdateService<Resource>>();
var controller = new BaseJsonApiController<Resource>(_jsonApiContextMock.Object, update: serviceMock.Object);
controller.ModelState.AddModelError("Id", "Failed Validation");

// act
var response = await controller.PatchAsync(id, resource);

// assert
serviceMock.Verify(m => m.UpdateAsync(id, It.IsAny<Resource>()), Times.Never);
Assert.IsType<BadRequestObjectResult>(response);
Assert.IsType<ErrorCollection>(((BadRequestObjectResult) response).Value);
}

[Fact]
public async Task PatchAsync_Throws_405_If_No_Service()
{
Expand All @@ -168,6 +190,46 @@ public async Task PatchAsync_Throws_405_If_No_Service()
Assert.Equal(405, exception.GetStatusCode());
}

[Fact]
public async Task PostAsync_Calls_Service()
{
// arrange
var resource = new Resource();
var serviceMock = new Mock<ICreateService<Resource>>();
_jsonApiContextMock.Setup(a => a.ApplyContext<Resource>(It.IsAny<BaseJsonApiController<Resource>>())).Returns(_jsonApiContextMock.Object);
_jsonApiContextMock.SetupGet(a => a.Options).Returns(new JsonApiOptions());
var controller = new BaseJsonApiController<Resource>(_jsonApiContextMock.Object, create: serviceMock.Object);
serviceMock.Setup(m => m.CreateAsync(It.IsAny<Resource>())).ReturnsAsync(resource);
controller.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext {HttpContext = new DefaultHttpContext()};

// act
await controller.PostAsync(resource);

// assert
serviceMock.Verify(m => m.CreateAsync(It.IsAny<Resource>()), Times.Once);
VerifyApplyContext();
}

[Fact]
public async Task PostAsync_ModelStateInvalid()
{
// arrange
var resource = new Resource();
var serviceMock = new Mock<ICreateService<Resource>>();
_jsonApiContextMock.Setup(a => a.ApplyContext<Resource>(It.IsAny<BaseJsonApiController<Resource>>())).Returns(_jsonApiContextMock.Object);
_jsonApiContextMock.SetupGet(a => a.Options).Returns(new JsonApiOptions());
var controller = new BaseJsonApiController<Resource>(_jsonApiContextMock.Object, create: serviceMock.Object);
controller.ModelState.AddModelError("Id", "Failed Validation");

// act
var response = await controller.PostAsync(resource);

// assert
serviceMock.Verify(m => m.CreateAsync(It.IsAny<Resource>()), Times.Never);
Assert.IsType<BadRequestObjectResult>(response);
Assert.IsType<ErrorCollection>(((BadRequestObjectResult)response).Value);
}

[Fact]
public async Task PatchRelationshipsAsync_Calls_Service()
{
Expand Down