Skip to content

Commit 0ab3522

Browse files
committed
fix(JsonApiReader): do not write to the response body stream
instead add an error to the ModelState
1 parent a8966ac commit 0ab3522

File tree

2 files changed

+7
-9
lines changed

2 files changed

+7
-9
lines changed

src/JsonApiDotNetCore/Formatters/JsonApiReader.cs

+6-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using System.IO;
3-
using System.Text;
43
using System.Threading.Tasks;
54
using JsonApiDotNetCore.Internal;
65
using JsonApiDotNetCore.Serialization;
@@ -16,7 +15,7 @@ public class JsonApiReader : IJsonApiReader
1615
private readonly IJsonApiDeSerializer _deSerializer;
1716
private readonly IJsonApiContext _jsonApiContext;
1817
private readonly ILogger<JsonApiReader> _logger;
19-
18+
2019

2120
public JsonApiReader(IJsonApiDeSerializer deSerializer, IJsonApiContext jsonApiContext, ILoggerFactory loggerFactory)
2221
{
@@ -37,26 +36,25 @@ public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
3736
try
3837
{
3938
var body = GetRequestBody(context.HttpContext.Request.Body);
40-
var model = _jsonApiContext.IsRelationshipPath ?
39+
var model = _jsonApiContext.IsRelationshipPath ?
4140
_deSerializer.DeserializeRelationship(body) :
4241
_deSerializer.Deserialize(body);
4342

44-
if(model == null)
43+
if (model == null)
4544
_logger?.LogError("An error occurred while de-serializing the payload");
4645

4746
return InputFormatterResult.SuccessAsync(model);
4847
}
4948
catch (JsonSerializationException ex)
5049
{
5150
_logger?.LogError(new EventId(), ex, "An error occurred while de-serializing the payload");
52-
context.HttpContext.Response.StatusCode = 422;
51+
context.ModelState.AddModelError(context.ModelName, ex, context.Metadata);
5352
return InputFormatterResult.FailureAsync();
5453
}
55-
catch(JsonApiException jex)
54+
catch (JsonApiException jex)
5655
{
5756
_logger?.LogError(new EventId(), jex, "An error occurred while de-serializing the payload");
58-
context.HttpContext.Response.StatusCode = jex.GetStatusCode();
59-
context.HttpContext.Response.Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jex.GetError())));
57+
context.ModelState.AddModelError(context.ModelName, jex, context.Metadata);
6058
return InputFormatterResult.FailureAsync();
6159
}
6260
}

src/JsonApiDotNetCore/JsonApiDotNetCore.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
3-
<VersionPrefix>2.1.0</VersionPrefix>
3+
<VersionPrefix>2.1.1</VersionPrefix>
44
<TargetFrameworks>netstandard1.6</TargetFrameworks>
55
<AssemblyName>JsonApiDotNetCore</AssemblyName>
66
<PackageId>JsonApiDotNetCore</PackageId>

0 commit comments

Comments
 (0)