简体   繁体   English

使用 c# api 上传文件时不支持的媒体类型 http 响应。

[英]Unsupported Media Type http response when upload file using c# api.

I am using angular and oi.file.js directive from https://github.com/tamtakoe/oi.file我正在使用来自https://github.com/tamtakoe/oi.file 的angular 和 oi.file.js 指令

My html looks like this:我的 html 看起来像这样:

<form name="EditOrder" enctype="multipart/form-data">
  <input type="file" oi-file="options">
</form>

Angular controller:角度控制器:

            $scope.file = {};

            $scope.options = {
                change: function (file) {
                    console.log($scope.file);
                    file.$upload('api/fileupload', $scope.file);
                    console.log($scope.file);
                }
            };

And C# api controller:和 C# api 控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using Ttmc.Core.Database;
using Ttmc.Core.Files;
using Ttmc.WebApp.Common;

namespace Ttmc.WebApp.Controllers
{
    public class FileUploadController: ApiController
    {
        private readonly FileRepository fileRepository;
        private readonly LogHelper<FileController> logHelper;
        private readonly SqlConnectionFactory sqlConnectionFactory;

        public FileUploadController()
        {
            logHelper = new LogHelper<FileController>();
            sqlConnectionFactory = new SqlConnectionFactory();
            fileRepository = new FileRepository(new DatabaseFileRepository(sqlConnectionFactory), sqlConnectionFactory);
        }

        [HttpPost]
        public HttpResponseMessage Post(FileController.PostFile postFile)
        {
            var request = HttpContext.Current.Request;
            HttpResponseMessage result = null;
            logHelper.LogExecute(() =>
            {
                if (request.Files.Count == 0)
                {
                    result = Request.CreateResponse(HttpStatusCode.BadRequest);
                }
                var resultFiles = new List<DatabaseFile>();
                using (var connection = sqlConnectionFactory.Create())
                using (var transaction = connection.BeginTransaction())
                {
                    for (var i = 0; i < request.Files.Count; i++)
                    {
                        var postedFile = request.Files[i];
                        var id = fileRepository.AddFile(postedFile.InputStream, postedFile.FileName, postFile.OrderId,
                                                        postFile.RootFolderName, connection, transaction);
                        resultFiles.Add(fileRepository.GetInfo(id, connection, transaction));
                    }
                    transaction.Commit();
                }
                result = Request.CreateResponse(HttpStatusCode.Created, resultFiles);
            });

            return result;
        }

        public class PostFile
        {
            public Guid OrderId { get; set; }
            public string RootFolderName { get; set; }
        }
    }
}

When I try to upload file I get Unsupported Media Type response.当我尝试上传文件时,我收到 Unsupported Media Type 响应。

POST /api/fileupload HTTP/1.1
Host: localhost:12345
Connection: keep-alive
Content-Length: 283
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost:12345
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)   Chrome/32.0.1700.76 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary6wBPmLUA5JPOBZYm
Accept: */*

Quite simple... I don't know what happened, but my method started to be invoked after I removed its parameter.很简单......我不知道发生了什么,但是我的方法在我删除它的参数后开始被调用。

public HttpResponseMessage Post() 

So the working method for file upload using C# API controller is:所以使用 C# API 控制器上传文件的工作方法是:

[HttpPost]
    public HttpResponseMessage Post()
    {
        var request = HttpContext.Current.Request;
        HttpResponseMessage result = null;
        logHelper.LogExecute(() =>
        {
            if (request.Files.Count == 0)
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            var resultFiles = new List<DatabaseFile>();
            using (var connection = sqlConnectionFactory.Create())
            using (var transaction = connection.BeginTransaction())
            {
                for (var i = 0; i < request.Files.Count; i++)
                {
                    var postedFile = request.Files[i];
                    var id = fileRepository.AddFile(postedFile.InputStream, postedFile.FileName, postFile.OrderId,
                                                    postFile.RootFolderName, connection, transaction);
                    resultFiles.Add(fileRepository.GetInfo(id, connection, transaction));
                }
                transaction.Commit();
            }
            result = Request.CreateResponse(HttpStatusCode.Created, resultFiles);
        });

        return result;
    }

In addition to k.makarov answer, Removing the parameter skips the multi-part content type check while posting.除了 k.makarov 答案之外,删除参数会在发布时跳过多部分内容类型检查。 Refer this article - Sending multi-part data.请参阅本文 - 发送多部分数据。 File and form data together 一起归档和表单数据

This line in the article specifically states - "Notice that the controller action does not take any parameters. That's because we process the request body inside the action, without invoking a media-type formatter. "文章中的这一行特别指出 - “请注意,控制器动作不带任何参数。那是因为我们在动作内部处理请求正文,而没有调用媒体类型格式化程序。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 API 响应 C# 中的“不支持的媒体类型” - API response “Unsupported Media Type” in C# 尝试在C#中使用Sony Camera Remote API时,HTTP / 1.1 415不支持的媒体类型? - HTTP/1.1 415 Unsupported Media Type when trying to use Sony Camera Remote API in C#? 上传文件时出现 415(不支持的媒体类型) - 415 (Unsupported Media Type) when upload file 使用Web API时不支持的媒体类型 - Unsupported Media Type when using Web API API Endpoint C# web API 不支持的媒体类型 - Unsupported Media Type for API Endpoint C# web API 使用$ http从角度发布到aspnetcore api时出现415不支持的媒体类型错误 - 415 unsupported media type error when posting to aspnetcore api from angular using $http 通过 C# class 发布到 API 时返回 415 不支持的媒体类型错误 - 415 Unsupported Media Type Error being returned when posting to API through C# class 在Web API中使用数组作为参数时出现不受支持的媒体类型错误? - Unsupported Media Type error when using array as parameter in web api? httpclient调用c#中不支持的媒体类型 - Unsupported media type in httpclient call c# Asp.Core API 尝试上传文件并存储在数据库中:错误:415:不支持的媒体类型 - Asp.Core API trying to upload file and store in database: ERROR: 415: Unsupported Media Type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM