【发布时间】:2019-05-20 11:52:37
【问题描述】:
我正在开发一项服务,该服务将使用 HTTP Content-Type: application/octet-stream 和 Transfer-Encoding: chunked 接收文件。
我能够让服务器获取请求DisableFormValueModelBinding 和RequestSizeLimit。
但是当我从 Request.Body 中获取数据时,长度始终为 0。
在框架中我会使用类似的东西 request.Content.ReadAsStreamAsync(); 但这似乎不是 Core 的选项。
我应该如何获取来自客户端(邮递员)的流内容?
使用 Postman,我尝试了 body 的 binary 和 form-data 选项,但是一旦它到达服务器,都没有最终拥有 body。通读一些文档,有关于创建使用 MultipartReader 的新格式化程序的建议。但这一切看起来都是基于我没有使用的 multipart/form-data 内容类型。我也尝试使用 curl 发送请求,但结果是一样的。
程序.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
控制器
[HttpPost]
[RequestSizeLimit(2147483648)] // https://stackoverflow.com/questions/43305220/form-key-or-value-length-limit-2048-exceeded
[DisableFormValueModelBinding] // https://dotnetcoretutorials.com/2017/03/12/uploading-files-asp-net-core/
public void Upload()
{
Request.EnableRewind();
Stream body = Request.Body;
Debug.WriteLine(body.Length);
}
【问题讨论】:
-
您是否在 Postman 中指定了“Body”?
-
@GabrielLuci 我做到了。我尝试了二进制和表单数据选项,但最终都没有实体。通读一些文档,有关于创建使用 MultipartReader 的新格式化程序的建议。但这一切看起来都是基于我没有使用的 multipart/form-data 内容类型。
-
@GabrielLuci 除非我错过阅读文档,否则 StreamFile 是他们创建的用于处理多部分数据的辅助方法。除非我误解了 MultipartReader 支持的内容,否则这不适用于我的情况。
-
对。这就说得通了。但我想我明白为什么它是 0。看看我的答案。
标签: c# .net-core asp.net-core-webapi