Skip to content

Commit 8e6a240

Browse files
committed
feat(content-negotiation): wire up reader and input formatter
1 parent a34ef20 commit 8e6a240

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Microsoft.AspNetCore.Mvc.Formatters;
4+
using Microsoft.Extensions.DependencyInjection;
5+
using Microsoft.Extensions.Primitives;
6+
7+
namespace JsonApiDotNetCore.Formatters
8+
{
9+
public class JsonApiOperationsInputFormatter : IInputFormatter
10+
{
11+
const string PROFILE_EXTENSION = "<http://example.org/profiles/myjsonstuff>; rel=\"profile\"";
12+
13+
public bool CanRead(InputFormatterContext context)
14+
{
15+
if (context == null)
16+
throw new ArgumentNullException(nameof(context));
17+
18+
var contentTypeString = context.HttpContext.Request.ContentType;
19+
20+
return (
21+
contentTypeString == "application/vnd.api+json" &&
22+
context.HttpContext.Request.Headers.TryGetValue("Link", out StringValues profileExtension) &&
23+
profileExtension == PROFILE_EXTENSION
24+
);
25+
}
26+
27+
public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
28+
{
29+
var reader = context.HttpContext.RequestServices.GetService<IJsonApiOperationsReader>();
30+
return await reader.ReadAsync(context);
31+
}
32+
}
33+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using System;
2+
using System.IO;
3+
using System.Threading.Tasks;
4+
using JsonApiDotNetCore.Internal;
5+
using JsonApiDotNetCore.Serialization;
6+
using JsonApiDotNetCore.Services;
7+
using Microsoft.AspNetCore.Mvc.Formatters;
8+
using Microsoft.Extensions.Logging;
9+
using Newtonsoft.Json;
10+
11+
namespace JsonApiDotNetCore.Formatters
12+
{
13+
public interface IJsonApiOperationsReader
14+
{
15+
Task<InputFormatterResult> ReadAsync(InputFormatterContext context);
16+
}
17+
18+
public class JsonApiOperationsReader : IJsonApiOperationsReader
19+
{
20+
public JsonApiOperationsReader()
21+
{
22+
}
23+
24+
public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
25+
{
26+
if (context == null)
27+
throw new ArgumentNullException(nameof(context));
28+
29+
var request = context.HttpContext.Request;
30+
if (request.ContentLength == 0)
31+
return InputFormatterResult.FailureAsync();
32+
33+
return InputFormatterResult.SuccessAsync(null);
34+
}
35+
36+
private string GetRequestBody(Stream body)
37+
{
38+
using (var reader = new StreamReader(body))
39+
{
40+
return reader.ReadToEnd();
41+
}
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)