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 all 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
10 changes: 10 additions & 0 deletions src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,16 @@ public class JsonApiOptions
/// </remarks>
public bool EnableOperations { get; set; }

/// <summary>
/// Whether or not to validate model state.
/// </summary>
/// <example>
/// <code>
/// options.ValidateModelState = true;
/// </code>
/// </example>
public bool ValidateModelState { get; set; }

[Obsolete("JsonContract resolver can now be set on SerializerSettings.")]
public IContractResolver JsonContractResolver
{
Expand Down
5 changes: 5 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,8 @@ public virtual async Task<IActionResult> PostAsync([FromBody] T entity)

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

entity = await _create.CreateAsync(entity);

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

if (entity == null)
return UnprocessableEntity();
if (_jsonApiContext.Options.ValidateModelState && !ModelState.IsValid)
return BadRequest(ModelState.ConvertToErrorCollection());

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

Expand Down
24 changes: 24 additions & 0 deletions src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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;
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
107 changes: 107 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 @@ -143,6 +146,8 @@ public async Task PatchAsync_Calls_Service()
const int id = 0;
var resource = new Resource();
var serviceMock = new Mock<IUpdateService<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, update: serviceMock.Object);

// act
Expand All @@ -153,6 +158,47 @@ public async Task PatchAsync_Calls_Service()
VerifyApplyContext();
}

[Fact]
public async Task PatchAsync_ModelStateInvalid_ValidateModelStateDisbled()
{
// arrange
const int id = 0;
var resource = new Resource();
var serviceMock = new Mock<IUpdateService<Resource>>();
_jsonApiContextMock.Setup(a => a.ApplyContext<Resource>(It.IsAny<BaseJsonApiController<Resource>>())).Returns(_jsonApiContextMock.Object);
_jsonApiContextMock.SetupGet(a => a.Options).Returns(new JsonApiOptions { ValidateModelState = false });
var controller = new BaseJsonApiController<Resource>(_jsonApiContextMock.Object, update: serviceMock.Object);

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

// assert
serviceMock.Verify(m => m.UpdateAsync(id, It.IsAny<Resource>()), Times.Once);
VerifyApplyContext();
Assert.IsNotType<BadRequestObjectResult>(response);
}

[Fact]
public async Task PatchAsync_ModelStateInvalid_ValidateModelStateEnabled()
{
// arrange
const int id = 0;
var resource = new Resource();
var serviceMock = new Mock<IUpdateService<Resource>>();
_jsonApiContextMock.Setup(a => a.ApplyContext<Resource>(It.IsAny<BaseJsonApiController<Resource>>())).Returns(_jsonApiContextMock.Object);
_jsonApiContextMock.SetupGet(a => a.Options).Returns(new JsonApiOptions{ValidateModelState = true});
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 +214,67 @@ 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_ValidateModelStateDisabled()
{
// 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 { ValidateModelState = false });
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
var response = await controller.PostAsync(resource);

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

[Fact]
public async Task PostAsync_ModelStateInvalid_ValidateModelStateEnabled()
{
// 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 { ValidateModelState = true });
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