我添加了一个上传方法(HTTPPOST)来上传一个简单的文件。我不断收到这个错误,不知道它来自哪里。有人可以解释一下吗?
也许有人也可以回答这个问题,这不是最重要的问题,但是您可以将文件扩展名过滤器传递给此操作过滤器吗?例如,它只接受 .csv 吗?或者那是我们以后应该在前端做的事情,就像在后端检查它已经上传时它有哪个扩展?
错误:1
邮寄方式:
[HttpPost]
[Consumes("multipart/form-data")]
public void Post(IFormFile file)
{
}
操作过滤器:
public class FormFileOperation : IOperationFilter
{
private const string FormDataMimeType = "multipart/form-data";
private static readonly string[] FormFilePropertyNames = typeof(IFormFile).GetTypeInfo().DeclaredProperties.Select(x => x.Name).ToArray();
public void Apply(Operation operation, OperationFilterContext context)
{
if (context.ApiDescription.ParameterDescriptions.Any(x => x.ModelMetadata.ContainerType == typeof(IFormFile)))
{
var formFileParameters = operation
.Parameters
.OfType<NonBodyParameter>()
.Where(x => FormFilePropertyNames.Contains(x.Name))
.ToArray();
var index = operation.Parameters.IndexOf(formFileParameters.First());
foreach (var formFileParameter in formFileParameters)
{
operation.Parameters.Remove(formFileParameter);
}
var formFileParameterName = context
.ApiDescription
.ActionDescriptor
.Parameters
.Where(x => x.ParameterType == typeof(IFormFile))
.Select(x => x.Name)
.First();
var parameter = new NonBodyParameter()
{
Name = formFileParameterName,
In = "formData",
Description = "The file to upload.",
Required = true,
Type = "file"
};
operation.Parameters.Insert(index, parameter);
if (!operation.Consumes.Contains(FormDataMimeType))
{
operation.Consumes.Add(FormDataMimeType);
}
}
}
}