简体   繁体   English

Javascript将POST JSON提取到WebAPI2 C#

[英]Javascript Fetch POST JSON to WebAPI2 C#

Have a ASP.Net Core full framework WebApi controller with the following controller method. 有一个具有以下控制器方法的ASP.Net Core完整框架WebApi控制器。

[HttpPost("{id}/json")]
public async Task<ILibraryModel> PostFromBody(int id, [FromBody]LibraryFilterOrder stuff, int pageSize, int pageNumber = 1)
{
    return await DoStuff(id, stuff, pageSize, pageNumber);
}

It is taking in a model of LibraryFilterOrder with the following definition. 它采用具有以下定义的LibraryFilterOrder模型。

public class LibraryFilterOrder
{
    public List<ContainerView.ContainerFilterType> Filters { get; set; }
    public List<ContainerView.ContainerOrderType> Orders { get; set; }
}

public class ContainerFilterType
{
   public string ColumnPrefix { get; set; }
   public string ColumnName { get; set; }
   public string FilterValue { get; set; }
}

public class ContainerOrderType
{
   public string ColumnPrefix { get; set; }
   public string ColumnName { get; set; }    
   public bool SortAscending { get; set; }
   public int SequenceId { get; set; }
}

Am using the Javascript Fetch API using Typescript 我正在使用Typescript使用Javascript Fetch API

fetch(`/api/Library/${pageIndex}/json?pageSize=${pageSize}&pageNumber=${pageNumber}`, {
                    method: "POST",
                    headers: {                        
                        'Content-Type': 'application/json; charset=utf-8'
                    },
                    body: JSON.stringify({ stuff: { filters: filters, orders : orders } })
                })
                .then(response => response.json() as Promise<LibraryModel>)
                .then(data => {
                   //DO stuff
                });

The Chrome Dev tools provides the following : Chrome开发工具提供以下功能: 在此处输入图片说明 With all of that the stuff variable in the controller is coming through with 2 properties of null. 有了所有这些,控制器中的填充变量将具有2个null属性。

Any help with this would be much appreciated, have been pulling my hair out for the last day or so trying to work it out, have taken the [FromBody] tag off of the parameter, and that still comes through as null. 对此的任何帮助将不胜感激,已经将我的头发拉到最后一天左右或试图解决它,将[FromBody]标记从参数中[FromBody]了,并且仍然以null表示。

You pass incorrect JSON. 您传递了不正确的JSON。

Change this line: 更改此行:

body: JSON.stringify({ stuff: { filters: filters, orders : orders } })

to this one: 对此:

body: JSON.stringify( { filters: filters, orders : orders } )

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM