Get error: "Deserialization of interface types is not supported" while sending request (with field and file) to .NET 6 Web API

huangapple go评论63阅读模式
英文:

Get error: "Deserialization of interface types is not supported" while sending request (with field and file) to .NET 6 Web API

问题

我正在练习在Angular中将值传递给表单,然后将其与文件一起发送到.NET 6 Web API。

以下是我所做的事情:

我的HTML组件:

<form [formGroup]="form" (ngSubmit)="submit()" enctype="multipart/form-data">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" formControlName="name"></td>
        </tr>

        <tr>
            <td>Price</td>
            <td><input type="text" formControlName="price"></td>
        </tr>

        <tr>
            <td>Quantity</td>
            <td><input type="text" formControlName="quantity"></td>
        </tr>

        <tr>
            <td>Description</td>
            <td><textarea formControlName="description" cols="30" rows="10"></textarea></td>
        </tr>

        <tr>
            <td>Status</td>
            <td><input type="checkbox" formControlName="status"></td>
        </tr>

        <tr>
            <td>Photo</td>
            <td>
                <input type="file" Name="photo" (change)="fileControl($event)">
            </td>
        </tr>

        <tr>
            <td>Category</td>
            <td>
                <select formControlName="categoryId">
                    <option value="1"> cate 1 </option>
                    <option value="2"> cate 2 </option>
                    <option value="3"> cate 3 </option>
                </select>
            </td>
        </tr>

        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" value="Save"></td>
        </tr>
    </table>
</form>

这是我的ts组件:

export class CreateApiComponent implements OnInit {
    form: FormGroup;
    file: any;

    constructor(
        private productApiService: ProductApiService,
        private formBuilder: FormBuilder,
        private datePipe : DatePipe
    ){}

    ngOnInit() { 
        this.form = this.formBuilder.group({
            name: '',
            price: 0,
            quantity: 0,
            status: true,
            description: '',
            photo: '',
            categoryId: 1
        })
    }

    fileControl(e:any) {
        this.file = e.target.files[0];
    }

    submit() {      
        let product: ProductApi = this.form.value;
        product.created = this.datePipe.transform(new Date(), 'dd/MM/yyyy');
        let formData = new FormData();
        formData.append('data', this.file);

        this.productApiService.createWithFile(product, formData).then(
            res => {
                this.result = do something ;
            },
            err => {
                console.log(err);                
            }
        )
    }
}

这是我的createWithFile函数,baseUrl只是一个包含"localhost:port/path"的字符串:

async createWithFile(product: Product, file: FormData) {
    return await lastValueFrom(this.httpClient.post(this.baseUrl+'create-with-file', {Product: product, Data: file}));
}

这是我的productApi类:

export class ProductApi {
    id: number;
    name: string;
    price: number;
    quantity: number;
    status: boolean;
    description: string;
    created: string;
    photo: string;
    categoryId: number;
    categoryName: string;
}

现在到我的ASP.NET,我正在使用Entity Framework:

这是我的Product类,Created属性有一个JsonConverter来处理它,所以不用担心:

public partial class Product
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public int? Quantity { get; set; }
    public string? Description { get; set; }
    public double? Price { get; set; }
    public bool Status { get; set; }
    public string? Photo { get; set; }
    public DateTime Created { get; set; }
    public int CategoryId { get; set; }
}

我还创建了一个模型来接收来自POST请求的参数:

public class CreatedUpload
{
    public Product Product { get; set; }
    public IFormFile Data { get; set; }        
}

这是我的控制器:

[HttpPost("create-with-file")]
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult CreateWithFile([FromBody] CreatedUpload createdUpload)
{
    try
    {
        *在这个位置,我放了一个调试以检查createdUpload中的数据*
        return Ok();
    }
    catch
    {
        return BadRequest();
    }
}

这是我期望的,我希望createdUpload从POST请求中捕获{Product: product, Data: file},但我得到了这个错误:

System.NotSupportedException: 不支持接口类型的反序列化。类型 'Microsoft.AspNetCore.Http.IFormFile'。路径:$.Data | LineNumber: 0 | BytePositionInLine: 144。

我还更改了CreateWithFile的参数,但它们都返回null(但不会引发错误):

[FromBody] Product product, [FromBody] IFormFile data
[FromForm] Product product, [FromForm] IFormFile data

我已经阅读了StackOverflow上的许多问题,但没有答案能够解决我的问题,我陷入了困境,请帮助我 Get error: "Deserialization of interface types is not supported" while sending request (with field and file) to .NET 6 Web API

英文:

I am practicing passing value to a form in Angular, and then sending it with a file to .NET 6 Web API.

Here is what I do:

My HTML component:

&lt;form [formGroup]=&quot;form&quot; (ngSubmit)=&quot;submit()&quot; enctype=&quot;multipart/form-data&quot;&gt;
    &lt;table&gt;
        &lt;tr&gt;
            &lt;td&gt;Name&lt;/td&gt;
            &lt;td&gt;&lt;input type=&quot;text&quot; formControlName=&quot;name&quot;&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;Price&lt;/td&gt;
            &lt;td&gt;&lt;input type=&quot;text&quot; formControlName=&quot;price&quot;&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;Quantity&lt;/td&gt;
            &lt;td&gt;&lt;input type=&quot;text&quot; formControlName=&quot;quantity&quot;&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;Description&lt;/td&gt;
            &lt;td&gt;&lt;textarea formControlName=&quot;description&quot; cols=&quot;30&quot; rows=&quot;10&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;Status&lt;/td&gt;
            &lt;td&gt;&lt;input type=&quot;checkbox&quot; formControlName=&quot;status&quot;&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;Photo&lt;/td&gt;
            &lt;td&gt;
                &lt;input type=&quot;file&quot; Name=&quot;photo&quot; (change)=&quot;fileControl($event)&quot;&gt;
            &lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;Category&lt;/td&gt;
            &lt;td&gt;
                &lt;select formControlName=&quot;categoryId&quot;&gt;
                    &lt;option value=&quot;1&quot;&gt; cate 1 &lt;/option&gt;
                    &lt;option value=&quot;2&quot;&gt; cate 2 &lt;/option&gt;
                    &lt;option value=&quot;3&quot;&gt; cate 3 &lt;/option&gt;
                &lt;/select&gt;
            &lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;&amp;nbsp;&lt;/td&gt;
            &lt;td&gt;&lt;input type=&quot;submit&quot; value=&quot;Save&quot;&gt;&lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
&lt;/form&gt;

And here is my ts component:

export class CreateApiComponent implements OnInit {
    form: FormGroup;
    file: any;

    constructor(
        private productApiService: ProductApiService,
        private formBuilder: FormBuilder,
        private datePipe : DatePipe
    ){}

    ngOnInit() { 
        this.form = this.formBuilder.group({
            name: &#39;&#39;,
            price: 0,
            quantity: 0,
            status: true,
            description: &#39;&#39;,
            photo: &#39;&#39;,
            categoryId: 1
        })

    }

    fileControl(e:any) {
        this.file = e.target.files[0];
    }

    submit() {      
        let product: ProductApi = this.form.value;
        product.created = this.datePipe.transform(new Date(), &#39;dd/MM/yyyy&#39;);
        let formData = new FormData();
        formData.append(&#39;data&#39;, this.file);

        this.productApiService.createWithFile(product, formData).then(
            res =&gt; {
                this.result = do something ;
            },
            err =&gt; {
                console.log(err);                
            }
        )
    }

}

And this is my createWithFile function, baseUrl is just a string containing "localhost:port/path":

async createWithFile(product: Product, file: FormData) {
    return await lastValueFrom(this.httpClient.post(this.baseUrl+&#39;create-with-file&#39;, {Product: product, Data: file}));
}

And this is my productApi class:

export class ProductApi {
    id: number;
    name: string;
    price: number;
    quantity: number;
    status: boolean;
    description: string;
    created: string;
    photo: string;
    categoryId: number;
    categoryName: string;
}

Now to my ASP.NET, I'm using Entity Framework:
This is my Product class, the Created property got a JsonConverter to take care of it so no worry:

public partial class Product
{
public int Id { get; set; }
public string? Name { get; set; }
public int? Quantity { get; set; }
public string? Description { get; set; }
public double? Price { get; set; }
public bool Status { get; set; }
public string? Photo { get; set; }
public DateTime Created { get; set; }
public int CategoryId { get; set; }
}

I also create a model to catch the param from post request:

public class CreatedUpload
{
    public Product Product { get; set; }
    public IFormFile Data { get; set; }        
}

This is my controller:

[HttpPost(&quot;create-with-file&quot;)]
[Consumes(&quot;application/json&quot;)]
[Produces(&quot;application/json&quot;)]
public IActionResult CreateWithFile([FromBody] CreatedUpload createdUpload)
{
    try
    {
        *at this spot i put a debug to check the data in createdUpload*
        return Ok();
    }
    catch
    {
        return BadRequest();
    }
}

Here is what I expect, I expect the createdUpload to catch {Product: product, Data: file} from the POST request, but instead I got this error:

> System.NotSupportedException: Deserialization of interface types is not supported. Type 'Microsoft.AspNetCore.Http.IFormFile'. Path: $.Data | LineNumber: 0 | BytePositionInLine: 144.

I also change the param of my CreateWithFile like this, but all of them return null (but not raise error):

[FromBody] Product product, [FromBody] IFormFile data
[FromForm] Product product, [FromForm] IFormFile data

I have read many questions in StackOverflow, but no answer can solve my problem, and I reach a dead end, please help me Get error: "Deserialization of interface types is not supported" while sending request (with field and file) to .NET 6 Web API

答案1

得分: 2

  1. 使用 FormData 将请求主体发送包含 product 对象和 file 的内容。
submit() {      
  let product: ProductApi = this.form.value;
  product.created = this.datePipe.transform(new Date(), 'dd/MM/yyyy');
  let formData = new FormData();
  formData.append('data', this.file);

  // 将键值对添加到 formData
  let key: keyof typeof product;
  for (k in product) {
    formData.append(`product.${k}`, product[k]);
  }

  this.productApiService.createWithFile(formData).then(
    res => {
      // 成功
    },
    err => {
      console.log(err);                
    }
  )
}
  1. 使用 formData 参数修改 createWithFile 方法签名。 使用 Angular HttpClient 发送请求,内容类型为 multipart/form-data
async createWithFile(formData: FormData){
    return await lastValueFrom(this.httpClient.post(this.baseUrl+'create-with-file', formData));
}
  1. 在 Web API 中,使用 FromForm 特性修改 CreateWithFile 操作,以接收 createdUpload 对象。
public IActionResult CreateWithFile([FromForm] CreatedUpload createdUpload)
英文:

You should send the request body with product object and file as FormData to API.

  1. Iterate the key properties of product object and add the key-value pair into formData. Note that it is required to have the prefix "product" in order to send the product object.
submit() {      
  let product: ProductApi = this.form.value;
  product.created = this.datePipe.transform(new Date(), &#39;dd/MM/yyyy&#39;);
  let formData = new FormData();
  formData.append(&#39;data&#39;, this.file);

  // Add key-value pair into formData
  let key: keyof typeof product;
  for (k in product) {
    formData.append(`product.${k}`, product[k]);
  }

  this.productApiService.createWithFile(formData).then(
    res =&gt; {
      // Success
    },
    err =&gt; {
      console.log(err);                
    }
  )
}
  1. Modify the createWithFile method signature with formData parameter. Post the formData. Angular HttpClient will post the request with content-type: multipart/form-data.
async createWithFile(formData: FormData){
    return await lastValueFrom(this.httpClient.post(this.baseUrl+&#39;create-with-file&#39;, formData));
}
  1. In Web API, modify the CreateWithFile action to receive the createdUpload object with the FromForm attribute.
public IActionResult CreateWithFile([FromForm] CreatedUpload createdUpload)

huangapple
  • 本文由 发表于 2023年2月16日 18:13:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定