165*_*plo 2 c# .net-core asp.net-core-webapi
我正在开发一项服务,该服务将使用 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 的新格式化程序的建议。但这一切看起来都基于我没有使用的多部分/表单数据内容类型。我也尝试使用 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>();
}
Run Code Online (Sandbox Code Playgroud)
启动文件
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();
}
}
Run Code Online (Sandbox Code Playgroud)
控制器
[HttpPost]
[RequestSizeLimit(2147483648)] // /sf/ask/3031365431/
[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);
}
Run Code Online (Sandbox Code Playgroud)
我读了你从那里得到的那篇文章[DisableFormValueModelBinding]。该属性的全部意义在于阻止 ASP.NET 读取正文。因此,为什么body.Length是 0 是有道理的。它只是还没有被读取(并且在您阅读整个内容之前您无法知道长度)。
但是您可以读取Content-Length请求的标头:
var length = Request.ContentLength;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2651 次 |
| 最近记录: |