Skip to content

Fixed: Casing convention in error response for invalid modal state #723

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 2 commits into from
May 8, 2020
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
3 changes: 1 addition & 2 deletions src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,7 @@ private string FormatResourceName(Type resourceType)

private string FormatPropertyName(PropertyInfo resourceProperty)
{
var contractResolver = (DefaultContractResolver)_options.SerializerSettings.ContractResolver;
return contractResolver.NamingStrategy.GetPropertyName(resourceProperty.Name, false);
return _options.SerializerContractResolver.NamingStrategy.GetPropertyName(resourceProperty.Name, false);
}
}
}
3 changes: 3 additions & 0 deletions src/JsonApiDotNetCore/Configuration/IJsonApiOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using JsonApiDotNetCore.Models;
using JsonApiDotNetCore.Models.JsonApiDocuments;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace JsonApiDotNetCore.Configuration
{
Expand Down Expand Up @@ -61,6 +62,8 @@ public interface IJsonApiOptions : ILinksConfiguration
/// </summary>
JsonSerializerSettings SerializerSettings { get; }

internal DefaultContractResolver SerializerContractResolver => (DefaultContractResolver)SerializerSettings.ContractResolver;

/// <summary>
/// Specifies the default query string capabilities that can be used on exposed json:api attributes.
/// Defaults to <see cref="AttrCapabilities.All"/>.
Expand Down
11 changes: 9 additions & 2 deletions src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using JsonApiDotNetCore.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;

namespace JsonApiDotNetCore.Controllers
{
Expand Down Expand Up @@ -114,7 +115,10 @@ public virtual async Task<IActionResult> PostAsync([FromBody] T entity)
throw new ResourceIdInPostRequestNotAllowedException();

if (_jsonApiOptions.ValidateModelState && !ModelState.IsValid)
throw new InvalidModelStateException(ModelState, typeof(T), _jsonApiOptions.IncludeExceptionStackTraceInErrors);
{
var namingStrategy = _jsonApiOptions.SerializerContractResolver.NamingStrategy;
throw new InvalidModelStateException(ModelState, typeof(T), _jsonApiOptions.IncludeExceptionStackTraceInErrors, namingStrategy);
}

entity = await _create.CreateAsync(entity);

Expand All @@ -130,7 +134,10 @@ public virtual async Task<IActionResult> PatchAsync(TId id, [FromBody] T entity)
throw new InvalidRequestBodyException(null, null, null);

if (_jsonApiOptions.ValidateModelState && !ModelState.IsValid)
throw new InvalidModelStateException(ModelState, typeof(T), _jsonApiOptions.IncludeExceptionStackTraceInErrors);
{
var namingStrategy = _jsonApiOptions.SerializerContractResolver.NamingStrategy;
throw new InvalidModelStateException(ModelState, typeof(T), _jsonApiOptions.IncludeExceptionStackTraceInErrors, namingStrategy);
}

var updatedEntity = await _update.UpdateAsync(id, entity);
return updatedEntity == null ? Ok(null) : Ok(updatedEntity);
Expand Down
10 changes: 5 additions & 5 deletions src/JsonApiDotNetCore/Exceptions/InvalidModelStateException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using JsonApiDotNetCore.Models;
using JsonApiDotNetCore.Models.JsonApiDocuments;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json.Serialization;

namespace JsonApiDotNetCore.Exceptions
{
Expand All @@ -17,13 +18,13 @@ public class InvalidModelStateException : Exception
public IList<Error> Errors { get; }

public InvalidModelStateException(ModelStateDictionary modelState, Type resourceType,
bool includeExceptionStackTraceInErrors)
bool includeExceptionStackTraceInErrors, NamingStrategy namingStrategy)
{
Errors = FromModelState(modelState, resourceType, includeExceptionStackTraceInErrors);
Errors = FromModelState(modelState, resourceType, includeExceptionStackTraceInErrors, namingStrategy);
}

private static List<Error> FromModelState(ModelStateDictionary modelState, Type resourceType,
bool includeExceptionStackTraceInErrors)
bool includeExceptionStackTraceInErrors, NamingStrategy namingStrategy)
{
List<Error> errors = new List<Error>();

Expand All @@ -32,9 +33,8 @@ private static List<Error> FromModelState(ModelStateDictionary modelState, Type
var propertyName = pair.Key;
PropertyInfo property = resourceType.GetProperty(propertyName);

// TODO: Need access to ResourceContext here, in order to determine attribute name when not explicitly set.
string attributeName =
property?.GetCustomAttribute<AttrAttribute>().PublicAttributeName ?? property?.Name;
property.GetCustomAttribute<AttrAttribute>().PublicAttributeName ?? namingStrategy.GetPropertyName(property.Name, false);

foreach (var modelError in pair.Value.Errors)
{
Expand Down
3 changes: 1 addition & 2 deletions src/JsonApiDotNetCore/Graph/ResourceNameFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ internal sealed class ResourceNameFormatter

public ResourceNameFormatter(IJsonApiOptions options)
{
var contractResolver = (DefaultContractResolver) options.SerializerSettings.ContractResolver;
_namingStrategy = contractResolver.NamingStrategy;
_namingStrategy = options.SerializerContractResolver.NamingStrategy;
}

/// <summary>
Expand Down
3 changes: 1 addition & 2 deletions src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,7 @@ private string TemplateFromResource(ControllerModel model)
/// </summary>
private string TemplateFromController(ControllerModel model)
{
var contractResolver = (DefaultContractResolver) _options.SerializerSettings.ContractResolver;
string controllerName = contractResolver.NamingStrategy.GetPropertyName(model.ControllerName, false);
string controllerName = _options.SerializerContractResolver.NamingStrategy.GetPropertyName(model.ControllerName, false);

var template = $"{_options.Namespace}/{controllerName}";
if (_registeredTemplates.Add(template))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public async Task When_posting_tag_with_invalid_name_it_must_fail()
Assert.Equal(HttpStatusCode.UnprocessableEntity, errorDocument.Errors[0].StatusCode);
Assert.Equal("Input validation failed.", errorDocument.Errors[0].Title);
Assert.Equal("The field Name must match the regular expression '^\\W$'.", errorDocument.Errors[0].Detail);
Assert.Equal("/data/attributes/Name", errorDocument.Errors[0].Source.Pointer);
Assert.Equal("/data/attributes/name", errorDocument.Errors[0].Source.Pointer);
}

[Fact]
Expand Down Expand Up @@ -127,7 +127,7 @@ public async Task When_patching_tag_with_invalid_name_it_must_fail()
Assert.Equal(HttpStatusCode.UnprocessableEntity, errorDocument.Errors[0].StatusCode);
Assert.Equal("Input validation failed.", errorDocument.Errors[0].Title);
Assert.Equal("The field Name must match the regular expression '^\\W$'.", errorDocument.Errors[0].Detail);
Assert.Equal("/data/attributes/Name", errorDocument.Errors[0].Source.Pointer);
Assert.Equal("/data/attributes/name", errorDocument.Errors[0].Source.Pointer);
}

[Fact]
Expand Down