问题描述
我想将文件上传到ASP Net Core Web API控制器操作方法。我将内容类型发送为应用程序/八位字节流。我创建了名为StreamInputFormatter的自定义输入格式化程序。 streaminputformatter被调用,但是控制器中的action方法未被调用?并且Iam收到错误消息
I want to upload file to asp net core web api controller action method. I am sending content-type as "application/octet-stream". I have created custom input formatter called StreamInputFormatter. The streaminputformatter is getting called, but the action method in controller is not getting called? and Iam getting error as
InvalidOperationException:该流不支持超时。
"InvalidOperationException: Timeouts are not supported on this stream."
StreamInputFormatter:
StreamInputFormatter:
public class StreamInputFormatter : IInputFormatter
{
public bool CanRead(InputFormatterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var contentType = context.HttpContext.Request.ContentType;
if (contentType == "application/octet-stream")
{
return true;
}
return false;
}
public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var memoryStream = new MemoryStream();
context.HttpContext.Request.Body.CopyTo(memoryStream);
return InputFormatterResult.SuccessAsync(memoryStream);
}
}
控制器操作方法:
[HttpPost("{documentType}")]
public async Task<IActionResult> CreateJob(string documentType, [FromBody]Stream template)
{
}
推荐答案
由于 DefaultObjectValidator
遍历不受支持的 Stream
属性(有关某些信息,请参见此)。
It sounds you are getting this error because of the DefaultObjectValidator
iterating over your unsupported Stream
properties (see this issue for some information).
要跳过流模型验证,可以添加
To skip Stream model validation, you could add
services.AddMvc(options =>
{
...
options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Stream)));
});
到您的配置。
这篇关于模型绑定无法与asp.net核心webapi控制器操作方法中的Stream类型参数一起使用(即使使用自定义streaminputformatter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!