blob: 2451ead6e17e9596e5913c2d0388b6e094f7d3fe (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using Timeline.Models;
namespace Timeline.Formatters
{
/// <summary>
/// Formatter that reads body as byte data.
/// </summary>
public class ByteDataInputFormatter : InputFormatter
{
/// <summary>
///
/// </summary>
public ByteDataInputFormatter()
{
SupportedMediaTypes.Add(MimeTypes.ImagePng);
SupportedMediaTypes.Add(MimeTypes.ImageJpeg);
SupportedMediaTypes.Add(MimeTypes.ImageGif);
SupportedMediaTypes.Add(MimeTypes.ImageWebp);
SupportedMediaTypes.Add(MimeTypes.TextPlain);
SupportedMediaTypes.Add(MimeTypes.TextMarkdown);
}
/// <inheritdoc/>
public override bool CanRead(InputFormatterContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (context.ModelType == typeof(ByteData))
return true;
return false;
}
/// <inheritdoc/>
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
var contentLength = request.ContentLength;
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ByteDataInputFormatter>>();
if (contentLength == null)
{
logger.LogInformation("Failed to read body as bytes. Content-Length is not set.");
return await InputFormatterResult.FailureAsync();
}
if (contentLength == 0)
{
logger.LogInformation("Failed to read body as bytes. Content-Length is 0.");
return await InputFormatterResult.FailureAsync();
}
var bodyStream = request.Body;
var data = new byte[contentLength.Value];
var bytesRead = await bodyStream.ReadAsync(data);
if (bytesRead != contentLength)
{
logger.LogInformation("Failed to read body as bytes. Actual length of body is smaller than Content-Length.");
return await InputFormatterResult.FailureAsync();
}
var extraByte = new byte[1];
if (await bodyStream.ReadAsync(extraByte) != 0)
{
logger.LogInformation("Failed to read body as bytes. Actual length of body is greater than Content-Length.");
return await InputFormatterResult.FailureAsync();
}
return await InputFormatterResult.SuccessAsync(new ByteData(data, request.ContentType));
}
}
}
|