.net4.6 webapi使用FromBody来获取multipart/form-data发送的文件,给出具体范例
时间: 2024-11-26 17:20:13 浏览: 21
在.NET Framework 4.6中的Web API(vNext版本),处理Multipart/form-data上传文件通常涉及到`System.Net.Http.Files`库和`Microsoft.AspNet.WebApi.Extensions.Formatters.HttpInputFormatter`的支持。`FromBody`属性用于标记一个控制器方法参数,以便Web API能够解析请求体并将其绑定到该参数。
首先,确保项目引用了以下NuGet包:
```sh
Install-Package Microsoft.AspNet.WebApi -Version 5.2.3 (或更高)
Install-Package Microsoft.AspNet.WebApi.Extensions -Version 5.2.3 (或更高)
```
然后,在控制器里,创建一个方法接收一个`IHttpActionResult`类型的结果,用来处理文件上传。你可以使用`HttpMediaTypeFormatter`来识别和处理Multipart数据:
```csharp
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace YourNamespace.Controllers
{
public class FileUploadController : ApiController
{
[HttpPost]
[Route("upload")]
public IHttpActionResult UploadFile([FromForm] MultipartFileContent file)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
// 检查文件是否为空或大小等
if (file.ContentLength == 0) return BadRequest("No file uploaded");
try
{
string rootPath = "YourAppFilesDirectory"; // 应用程序文件存储路径
string filePath = Path.Combine(rootPath, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.InputStream.CopyToAsync(stream);
}
return Ok("File uploaded successfully.");
}
catch (Exception ex)
{
return InternalServerError(ex.Message);
}
}
private IHttpActionResult InternalServerError(string message)
{
return StatusCode((int)HttpStatusCode.InternalServerError, message);
}
}
// Custom model binder for handling MultipartFileContent
public class MultipartFileContentModelBinder : ModelBinderProvider
{
public override IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Configuration.Formatters.MultipartJsonFormatter != null)
{
return new MultipartFileContentBinder(context.Configuration.Formatters.MultipartJsonFormatter);
}
else
{
return null;
}
}
}
// MultipartFileContentBinder implementation
public class MultipartFileContentBinder : IModelBinder
{
private readonly MultipartMemoryStreamProvider _memoryStreamProvider;
public MultipartFileContentBinder(MultipartMemoryStreamProvider memoryStreamProvider)
{
_memoryStreamProvider = memoryStreamProvider;
}
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
var fileContent = (MultipartFileContent)await valueProviderResult.FirstValue.GetSingleValueAsync();
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, fileContent);
return Task.CompletedTask;
}
}
}
```
在这个示例中,`MultipartFileContent`是一个自定义模型,你可以根据实际需求进行扩展。`MultipartFileContentModelBinder`提供了一个适配器,使得Web API能正确地识别并处理Multipart请求。
阅读全文