模型绑定流实例

时间:2018-12-11 07:45:14

标签: c# asp.net-core asp.net-core-2.1

我想将流文件上传到控制器,它的方法是从抽象控制器实现的。绑定流;

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,","multipart/form-data" };

    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);
    }
}

每当我向引发错误的方法发送请求时:

  

无法创建类型为'System.IO.Stream'的实例。模型绑定的复杂类型不能为抽象或值类型,并且必须具有无参数的构造函数。

这是我的控制人

public override async Task<IActionResult> PostParentChildAvatar([FromForm] Stream file)
{
    var accountName = _configuration.GetValue<string>(AccountName);
    var key = _configuration.GetValue<string>(Key);
    var blobServiceEndpoint = _configuration.GetValue<string>(BlobServiceEndpoint);
    var containerName = _configuration.GetValue<string>(ContainerName);

    var storageService = new StorageService(accountName, key, blobServiceEndpoint, containerName);

    var avatar = await storageService.CreateFileWithStreamAsync(file);

    return Ok(new AvatarViewModel()
    {
        Id = Guid.Parse(avatar.Id.Substring(0,avatar.Id.Length - 4)),
        Url = avatar.FileUrl
    });
}

0 个答案:

没有答案