415尝试拦截POST请求时出现UnsupportedMediaType

时间:2019-12-09 20:57:25

标签: .net api asp.net-core gzip ziparchive

我的供稿提供商通过POST请求向我的服务器发送了一个.gz文件(zip文件)。

我正在尝试实现.NET代码,该代码将拦截POST请求并解压缩文件以在其中打开文件。

我只是想拦截POST请求并解压缩内容:

namespace app.Controllers
{
    [Route("")]
    public class FeedController : Controller
    {
        [HttpPost]
        public string Post([FromBody] string content)
        {
            return content;
        }
    }
}

它返回415 UnsupportedMediaType。

如何拦截POST请求(ZIP文件),以及如何解压缩该请求以将文件返回到内部?

谢谢。

编辑:

[HttpPost]
        [Consumes("multipart/form-data")]
        public IActionResult Post(IFormFile file)
        {
            if (file == null)
                return BadRequest();

            try
            {
                using (var zip = new ZipArchive(file.OpenReadStream()))
                {
                    // do stuff with the zip file
                }
            }
            catch
            {
                return BadRequest();
            }

            return Ok();
        }

2 个答案:

答案 0 :(得分:0)

部分问题得到解决。

要读取POST请求发送的.gz文件,您应该执行以下操作:

[HttpPost]
        [Consumes("application/gzip")]
        public IActionResult Post(IFormFile file)
        {

                WebClient Client = new WebClient();
                Client.DownloadFile("http://xxxxxx.com/feed.gz", "C:\\temp\\mygzipfile.gz");
                // do something with this file
            return Ok();
        }

答案 1 :(得分:-1)

您是否缺少ContentType标头? Check out this case以获得更多详细信息。