Multipart/form -data asp.net核心6后端-415未支撑的媒体类型

发布于 2025-01-21 10:07:58 字数 1835 浏览 0 评论 0原文

我有一个最小的API(或Web API?),该API应该接收表单数据(字段,以及文件)。

我读到,我必须用[From Form]来装饰端点才能获取数据,但它不起作用。

提交表格时,我会遇到错误(415个不支持的媒体类型) 它甚至没有到达应该在控制台上“接收”的地步。

我还尝试从Postman发送一个表单数据,同样的错误会返回(415)

这是我的代码:

const onSubmit = async (data: any) => {
    setUploading(true);
    // Add form values to formdata, including files
    let formData = new FormData();
    for (let key in data) {
      if (key === "file") {
        data.file.forEach((f: any) => {
          formData.append("file", f.originFileObj);
        });
        continue;
      }
      formData.append(key, data[key]);
    }

    try {
      const response = await axios.post("http://localhost:5210/file", formData, { headers: { "Content-Type": "multipart/form-data" } });
      message.success("File sent successfully!");
      form.resetFields();
    } catch (error: any) {
      console.log(error.response.data);
    }
    setUploading(false);
  };
using Microsoft.AspNetCore.Mvc;

var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(args);
builder.Services.AddCors(options=> options.AddDefaultPolicy(builder => {builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();} ));

var app = builder.Build();
app.UseCors();

app.MapPost("/file" ,([FromForm] FormData data)=>{
    System.Console.WriteLine("Received");
     return data;
});

app.Run();

我的formdata class:

public class FormData
{
    public string? firstName { get; set; }
    public string? lastName { get; set; }
    public string? company { get; set; }
    public string? sendTo { get; set; }
    public IFormCollection? files { get; set;}
}

I have a minimal API (or Web API?) that should receive form data (fields, plus a file).

I read that I have to decorate my endpoint with [FromForm] to get the data, but it's not working.

When I submit the form, I get an error (415 unsupported media type)
it doesn't even get to the point where it should print "Received" on the console.

I also tried sending a form-data from postman and the same error comes back (415)

Here is my code:

const onSubmit = async (data: any) => {
    setUploading(true);
    // Add form values to formdata, including files
    let formData = new FormData();
    for (let key in data) {
      if (key === "file") {
        data.file.forEach((f: any) => {
          formData.append("file", f.originFileObj);
        });
        continue;
      }
      formData.append(key, data[key]);
    }

    try {
      const response = await axios.post("http://localhost:5210/file", formData, { headers: { "Content-Type": "multipart/form-data" } });
      message.success("File sent successfully!");
      form.resetFields();
    } catch (error: any) {
      console.log(error.response.data);
    }
    setUploading(false);
  };
using Microsoft.AspNetCore.Mvc;

var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(args);
builder.Services.AddCors(options=> options.AddDefaultPolicy(builder => {builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();} ));

var app = builder.Build();
app.UseCors();

app.MapPost("/file" ,([FromForm] FormData data)=>{
    System.Console.WriteLine("Received");
     return data;
});

app.Run();

My FormData class :

public class FormData
{
    public string? firstName { get; set; }
    public string? lastName { get; set; }
    public string? company { get; set; }
    public string? sendTo { get; set; }
    public IFormCollection? files { get; set;}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

征棹 2025-01-28 10:07:58

在此处找到解决方案:
.net 6 Minimal api and Multipart/form-data

什么我要做的就是删除[从Form],因为它看起来不再由.NET 6支持。 aspnet/core/fultagals/minimal-apis?view = aspnetcore-6.0#explicit-parameter-binding“ rel =“ nofollow noreferrer”> https://learlen.microsoft.com/en-us/en-us/aspnet/aspnet/core/core/fundamentals/minimal/minimal/minimal- -apis?view = aspnetcore-6.0#explicit-parameter-binding )

我也不需要模型(formdata)类才能工作。

将我的终点更改为解决我的问题,

app.MapPost("/file",(HttpContext ctx)=> {

    var data = ctx.Request.Form; // form data is stored here
    var files = ctx.Request.Form.Files; // files are stored here
    
    return "Success";
    });

因为返回数据的方式有些丑陋,所以现在我的下一个目标是清理它,但这是一个不同的话题。

这就是数据的样子:

[
    {
        "key": "firstName",
        "value": [
            "Mike"
        ]
    },
    {
        "key": "lastName",
        "value": [
            "Jones"
        ]
    },
    {
        "key": "company",
        "value": [
            "123Net"
        ]
    },
    {
        "key": "sendTo",
        "value": [
            "Someone"
        ]
    }
]

Found solution here:
.NET 6 Minimal API and multipart/form-data

What i had to do is remove [FromForm] as it looks like it is no longer supported by .Net 6. (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0#explicit-parameter-binding)

I also don't need the Model (FormData) class for this to work.

Changing my endpoint to this solved my issue

app.MapPost("/file",(HttpContext ctx)=> {

    var data = ctx.Request.Form; // form data is stored here
    var files = ctx.Request.Form.Files; // files are stored here
    
    return "Success";
    });

the way the data is returned is a bit ugly, so now my next goal is to clean it up, but that is a different topic.

this is what data looks like:

[
    {
        "key": "firstName",
        "value": [
            "Mike"
        ]
    },
    {
        "key": "lastName",
        "value": [
            "Jones"
        ]
    },
    {
        "key": "company",
        "value": [
            "123Net"
        ]
    },
    {
        "key": "sendTo",
        "value": [
            "Someone"
        ]
    }
]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文