簡體   English   中英

錯誤 415:不支持的媒體類型 - ASP.NET MVC

[英]Error 415: Unsupported Media Type - ASP.NET MVC

我正在使用此 Kotlin 教程的代碼將文件上傳到我的 ASP.NET MVC Core API。 該代碼正在編譯並且似乎正在運行。 但我不知道如何在我的 API 上接收它。

這是我用來接收文件的代碼:

public interface IFormFile
{
    string ContentType { get; }
    string ContentDisposition { get; }
    IHeaderDictionary Headers { get; }
    long Length { get; }
    string Name { get; }
    string FileName { get; }
    Stream OpenReadStream();
    void CopyTo(Stream target);
    Task CopyToAsync(Stream target, CancellationToken cancellationToken);
}

[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile formFile)
{
    if (formFile.Length > 0)
    {
        Console.WriteLine("TEST");
        
        // full path to file in temp location
        var filePath = Path.GetTempFileName(); //we are using Temp file name just for the example. Add your own file path.
        //filePaths.Add(filePath);
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await formFile.CopyToAsync(stream, CancellationToken.None);
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.
    return Ok();
}

發送文件時,我收到以下錯誤響應:

I/System.out: FILE RESP Response{protocol=http/1.1, code=415, message=Unsupported Media Type, url=http://10.0.2.2:5000/api/google/upload}

我嘗試了多個教程,但這是一個很難解決的問題。 我在 C# 代碼中做錯了什么?

編輯:我已將我的問題最小化,如下:

[HttpPost("upload")]
public IActionResult Upload([FromForm] IFormFile file)
{

     Console.WriteLine("TESTT " + file.Name);
     return Ok();
}

這個非常基本的代碼也失敗了。 我使用 Insomnia 發送了一個文件,這是我收到的錯誤:

System.NullReferenceException: Object reference not set to an instance of an object.
   at RestService.Controllers.GoogleController.Upload(IFormFile file) in /Users/niel/School/integratieproject4/dotnet/Project/Core/API/Controllers/GoogleController.cs:line 49

我的 C# 沒有以任何方式接收文件。

您應該安排格式類型。 將格式從文本更改為 JSON。 它會起作用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM