Skip to content

fix(#313): Do not return 409 for generic InvalidCastException #375

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 1 commit into from
Aug 11, 2018
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
24 changes: 12 additions & 12 deletions src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using JsonApiDotNetCore.Services.Operations.Processors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

Expand Down Expand Up @@ -44,12 +45,7 @@ public static IServiceCollection AddJsonApi<TContext>(this IServiceCollection se

config.BuildContextGraph(builder => builder.AddDbContext<TContext>());

mvcBuilder
.AddMvcOptions(opt =>
{
opt.Filters.Add(typeof(JsonApiExceptionFilter));
opt.SerializeAsJsonApi(config);
});
mvcBuilder.AddMvcOptions(opt => AddMvcOptions(opt, config));

AddJsonApiInternals<TContext>(services, config);
return services;
Expand All @@ -63,17 +59,19 @@ public static IServiceCollection AddJsonApi(this IServiceCollection services,

options(config);

mvcBuilder
.AddMvcOptions(opt =>
{
opt.Filters.Add(typeof(JsonApiExceptionFilter));
opt.SerializeAsJsonApi(config);
});
mvcBuilder.AddMvcOptions(opt => AddMvcOptions(opt, config));

AddJsonApiInternals(services, config);
return services;
}

private static void AddMvcOptions(MvcOptions options, JsonApiOptions config)
{
options.Filters.Add(typeof(JsonApiExceptionFilter));
options.Filters.Add(typeof(TypeMatchFilter));
options.SerializeAsJsonApi(config);
}

public static void AddJsonApiInternals<TContext>(
this IServiceCollection services,
JsonApiOptions jsonApiOptions) where TContext : DbContext
Expand Down Expand Up @@ -141,6 +139,8 @@ public static void AddJsonApiInternals(
services.AddScoped<IQueryParser, QueryParser>();
services.AddScoped<IControllerContext, Services.ControllerContext>();
services.AddScoped<IDocumentBuilderOptionsProvider, DocumentBuilderOptionsProvider>();

// services.AddScoped<IActionFilter, TypeMatchFilter>();
}

private static void AddOperationServices(IServiceCollection services)
Expand Down
8 changes: 0 additions & 8 deletions src/JsonApiDotNetCore/Internal/JsonApiExceptionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,6 @@ public static JsonApiException GetException(Exception exception)
if (exceptionType == typeof(JsonApiException))
return (JsonApiException)exception;

// TODO: this is for mismatching type requests (e.g. posting an author to articles endpoint)
// however, we can't actually guarantee that this is the source of this exception
// we should probably use an action filter or when we improve the ContextGraph
// we might be able to skip most of deserialization entirely by checking the JToken
// directly
if (exceptionType == typeof(InvalidCastException))
return new JsonApiException(409, exception.Message, exception);

return new JsonApiException(500, exceptionType.Name, exception);
}
}
Expand Down
49 changes: 49 additions & 0 deletions src/JsonApiDotNetCore/Middleware/TypeMatchFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using System.Linq;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

namespace JsonApiDotNetCore.Middleware
{
public class TypeMatchFilter : IActionFilter
{
private readonly IJsonApiContext _jsonApiContext;

public TypeMatchFilter(IJsonApiContext jsonApiContext)
{
_jsonApiContext = jsonApiContext;
}

/// <summary>
/// Used to verify the incoming type matches the target type, else return a 409
/// </summary>
public void OnActionExecuting(ActionExecutingContext context)
{
var request = context.HttpContext.Request;
if (IsJsonApiRequest(request) && request.Method == "PATCH" || request.Method == "POST")
{
var deserializedType = context.ActionArguments.FirstOrDefault().Value?.GetType();
var targetType = context.ActionDescriptor.Parameters.FirstOrDefault()?.ParameterType;

if (deserializedType != null && targetType != null && deserializedType != targetType)
{
var expectedJsonApiResource = _jsonApiContext.ContextGraph.GetContextEntity(targetType);

throw new JsonApiException(409,
$"Cannot '{context.HttpContext.Request.Method}' type '{_jsonApiContext.RequestEntity.EntityName}' "
+ $"to '{expectedJsonApiResource?.EntityName}' endpoint.",
detail: "Check that the request payload type matches the type expected by this endpoint.");
}
}
}

private bool IsJsonApiRequest(HttpRequest request)
{
return (request.ContentType?.Equals(Constants.ContentType, StringComparison.OrdinalIgnoreCase) == true);
}

public void OnActionExecuted(ActionExecutedContext context) { /* noop */ }
}
}