本文介绍了模型绑定不适用于 asp.net 核心 webapi 控制器操作方法中的 Stream 类型参数.(即使使用自定义 streaminputformatter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件上传到 asp net core web api 控制器操作方法.我将内容类型作为应用程序/八位字节流"发送.我创建了名为 StreamInputFormatter 的自定义输入格式化程序.streaminputformatter 被调用,但控制器中的 action 方法没有被调用?并且我收到错误为

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)
        {

        }

推荐答案

对于任何为此寻找完整示例的人,以下内容可能会有所帮助:

For anyone looking for the full example for this, the following might help:

Startup.cs

services.AddMvc(options =>
{
    options.InputFormatters.Add(new StreamInputFormatter());
    options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Stream)));
});

StreamInputFormatter.cs

StreamInputFormatter.cs

public class StreamInputFormatter : IInputFormatter
{
    // enter your list here...
    private readonly List<string> _allowedMimeTypes = new List<string>
        { "application/pdf", "image/jpg", "image/jpeg", "image/png", "image/tiff", "image/tif", "application/octet-stream" };


    public bool CanRead(InputFormatterContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        var contentType = context.HttpContext.Request.ContentType;
        if (_allowedMimeTypes.Any(x => x.Contains(contentType)))
        {
            return true;
        }

        return false;
    }

    public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        // enable stream rewind or you won't be able to read the file in the controller   
        var req = context.HttpContext.Request;
        req.EnableRewind();

        var memoryStream = new MemoryStream();
        context.HttpContext.Request.Body.CopyTo(memoryStream);
        req.Body.Seek(0, SeekOrigin.Begin);
        return InputFormatterResult.SuccessAsync(memoryStream);
    }
}

然后是控制器:

public class FileController : BaseController
{
    [HttpPost("customer/{customerId}/file", Name = "UploadFile")]
    [SwaggerResponse(StatusCodes.Status201Created, typeof(UploadFileResponse))]
    [Consumes("application/octet-stream", new string[] { "application/pdf", "image/jpg", "image/jpeg", "image/png", "image/tiff", "image/tif"})]
    public async Task<IActionResult> UploadFile([FromBody] Stream file, [FromRoute] string customerId, [FromQuery] FileQueryParameters queryParameters)
    {
        // file processing here
    }
}

这篇关于模型绑定不适用于 asp.net 核心 webapi 控制器操作方法中的 Stream 类型参数.(即使使用自定义 streaminputformatter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:58