角度上载文件和附加数据ASP WebAPI

时间:2016-02-24 10:39:33

标签: c# asp.net angularjs asp.net-web-api ng-file-upload

我正在尝试将包含一些文本字段和文件的表单上传到我的WebAPI。目前我总是得到415错误(ASP控制器中的断点不会被击中)。我的代码如下所示:

角色服务

// 'Upload' is from ng-file-upload
function applicationService(settings, $http, Upload) {
  var createCustomApplication = function(application) {
    var url = settings.baseUrl + '/api/applications/custom';

    var data = new FormData();
    angular.forEach(application, function (value, key) {
      data.append(key, value);
    });

    return Upload.upload({
      url: url,
      data: data,
      method: 'POST'
    });
  };

  return {
    createCustomApplication: createCustomApplication
  }
}

WebAPI控制器

[ResponseType(typeof(ApplicationModel))]
[HttpPost, Route("api/applications/custom")]
public IHttpActionResult CreateCustomApplication([FromBody]ApplicationModel application)
{
   var file = HttpContext.Current.Request.Files[0];
   return Ok();
}

3 个答案:

答案 0 :(得分:1)

如果要将包含文件作为参数的表单包含在操作中,则需要添加自定义媒体格式化程序。 Fortunately someone already created a Nuget-package for this。配置很简单。安装软件包并在WebApiConfig文件中添加一行。

此软件包允许您使用HttpFile - 对象,该对象直接将您的文件作为参数或在模型内捕获。 From the docs

[HttpPost]
public void PostFileBindRawFormData(MultipartDataMediaFormatter.Infrastructure.FormData formData)
{
    HttpFile file;
    formData.TryGetValue(<key>, out file);
}

public class PersonModel
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public DateTime? BirthDate {get; set;}
    public HttpFile AvatarImage {get; set;}
    public List<HttpFile> Attachments {get; set;}
    public List<PersonModel> ConnectedPersons {get; set;}
}

//api controller example
[HttpPost]
public void PostPerson(PersonModel model)
{
    //do something with the model
}

答案 1 :(得分:0)

你的代码与我使用的代码非常相似。问题可能与multipart / form-data标头值有关。我没有足够的经验来说明你的实现有什么问题,但也许尝试这种备用异步等待方法。

[Route("api/applications/custom")]
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
    MultipartMemoryStreamProvider memoryStreamProvider;
    try
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        memoryStreamProvider = await Request.Content.ReadAsMultipartAsync();
    }
    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, string.Format("An error has occured while uploading your file. Error details: '{0}'", e.Message));    
    }

    // do something with your file...

    return Request.CreateResponse(HttpStatusCode.OK);

}

这是我的JS代码。我也使用promises而不是上传函数返回的内容(如果有的话)。

$scope.submit = function() {
    if ($scope.form.file.$valid && $scope.file) {
        $scope.upload($scope.file);
    }
};

$scope.upload = function(file) {

    Upload.upload({
        url: 'api/applications/custom',
        data: { file: file }
    }).then(function(response) {
        // report the success to the user
    }, function(response) {
        // report the error to the user
    }, function(evt) {
        // report the progress of the upload to the user
        $scope.uploadProgress = evt.loaded / evt.total;
    });
};

我使用以下文章作为我的解决方案的基础:http://monox.mono-software.com/blog/post/Mono/233/Async-upload-using-angular-file-upload-directive-and-net-WebAPI-service/

答案 2 :(得分:-1)

我有同样的问题。 您应该在POST请求中添加内容类型。

headers: {
     'Content-Type': undefined
},
相关问题