【问题标题】:Upload a file and also pass model data上传文件并传递模型数据
【发布时间】:2019-10-21 06:05:33
【问题描述】:

我需要导入一个文件,以及下面显示的Person 模型。

我可以上传文件,但是我无法在我编写的importFileAndOtherInfo 方法中检索 Person 模型数据。

注意:我正在通过 Postman 测试这个 Web API。如何上传文件,并通过 Postman 发送 Person 模型数据?

int pId
string PName
School schoolAttended

我的实现:

[HttpPost]
public async Task<int> importFileAndOtherInfo(Person person)
{

    var stream = HttpContext.Current.Request.Files[0].InputStream

    // HOW TO RETRIEVE THE PERSON DATA HERE.

}

【问题讨论】:

标签: c# asp.net-web-api postman


【解决方案1】:

我在 netcoreapp2.2 中使用相同的。成功运行。

现在,当我从 notecoreapp2.2 迁移到 netcoreapp3.1 时,我遇到了 private readonly IOptions&lt;MvcJsonOptions&gt; _jsonOptions; 的问题

MvcJsonOptions 是从核心 2.2 到 3.0 的重大变化。

检查这个: Migration of netcoreapp2.2 to netcoreapp3.1 - convert MvcJsonOptions to core3.1 compatable

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

我从您的问题中了解到,您想同时传递模型数据和流中的文件;不能直接发送,方法是用IFormFile发送文件并添加创建自己的模型绑定器,如下所示,

public class JsonWithFilesFormDataModelBinder: IModelBinder
{
    private readonly IOptions<MvcJsonOptions> _jsonOptions;
    private readonly FormFileModelBinder _formFileModelBinder;

    public JsonWithFilesFormDataModelBinder(IOptions<MvcJsonOptions> jsonOptions, ILoggerFactory loggerFactory)
    {
        _jsonOptions = jsonOptions;
        _formFileModelBinder = new FormFileModelBinder(loggerFactory);
    }

    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        // Retrieve the form part containing the JSON
        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.FieldName);
        if (valueResult == ValueProviderResult.None)
        {
            // The JSON was not found
            var message = bindingContext.ModelMetadata.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(bindingContext.FieldName);
            bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, message);
            return;
        }

        var rawValue = valueResult.FirstValue;

        // Deserialize the JSON
        var model = JsonConvert.DeserializeObject(rawValue, bindingContext.ModelType, _jsonOptions.Value.SerializerSettings);

        // Now, bind each of the IFormFile properties from the other form parts
        foreach (var property in bindingContext.ModelMetadata.Properties)
        {
            if (property.ModelType != typeof(IFormFile))
                continue;

            var fieldName = property.BinderModelName ?? property.PropertyName;
            var modelName = fieldName;
            var propertyModel = property.PropertyGetter(bindingContext.Model);
            ModelBindingResult propertyResult;
            using (bindingContext.EnterNestedScope(property, fieldName, modelName, propertyModel))
            {
                await _formFileModelBinder.BindModelAsync(bindingContext);
                propertyResult = bindingContext.Result;
            }

            if (propertyResult.IsModelSet)
            {
                // The IFormFile was successfully bound, assign it to the corresponding property of the model
                property.PropertySetter(model, propertyResult.Model);
            }
            else if (property.IsBindingRequired)
            {
                var message = property.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(fieldName);
                bindingContext.ModelState.TryAddModelError(modelName, message);
            }
        }

        // Set the successfully constructed model as the result of the model binding
        bindingContext.Result = ModelBindingResult.Success(model);
    }
} 

型号

[ModelBinder(typeof(JsonWithFilesFormDataModelBinder), Name = "data")]
public class Person
{
   public int pId {get; set;}
   public string PName {get; set;}
   public School schoolAttended {get; set;}
   public IFormFile File { get; set; }
}

邮递员请求:

【讨论】:

    猜你喜欢
    • 2016-07-15
    • 2018-06-23
    • 2016-06-21
    • 2015-07-10
    • 2021-05-25
    • 2015-08-05
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    相关资源
    最近更新 更多