简体   繁体   中英

Javascript Fetch POST JSON to WebAPI2 C#

Have a ASP.Net Core full framework WebApi controller with the following controller method.

[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.

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

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 : 在此处输入图片说明 With all of that the stuff variable in the controller is coming through with 2 properties of 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.

You pass incorrect JSON.

Change this line:

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

to this one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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