ASP.Net Core 3.1:控制器方法始终从HttpPost调用中接收NULL参数

我已经使用带有MVC模式的ASP.Net Core 3.1创建了一个全新的Visual Studio 2019 Web应用程序。

我的控制器有一个HttpPost方法,该方法应该有一个传入的Json对象(我​​将[FromBody]用作传入的参数)。

无论我尝试什么,传入的参数始终为Null。我尝试将参数更改为字符串,并将Model修改为一个简单的3字段类,但它仍为null。

我使用Chrome的开发人员工具来确保我的页面从JavaScript Post回调正确发送了Json对象(并且还使用Postman进行了相同操作),结果相同:我的参数仍然为Null。

我需要怎么做才能使参数作为实际值输入?

我的控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

using canvasApiLib.API;
using CanvasGrades.Models.AuxiliaryModels;

namespace CanvasGrades.Controllers
{
    public class FinalGradeController : Controller
    {

        public async Task<IactionResult> Index()
        {
            // Course Name
            dynamic courseDetails = await clsCoursesApi.getcourseDetails(accessToken,apiUrl,canvasCourseId);
            ViewData["CourseName"] = courseDetails.name;

            // Course Term
            dynamic courseTerm = await clsEnrollmentTermsApi.getEnrollmentTerm(accessToken,canvasaccountID,termNum);
            ViewData["CourseTerm"] = courseTerm.name;

            return View();
        }

        [HttpPost]
        public async Task<IactionResult> LoadTable([FromBody]DTParameters dtParameters)
        {
            //DTParameters dtParameters = new DTParameters();

            if (dtParameters == null)
            {
                dtParameters = new DTParameters();
            }
        }
    }
}

我的DTParameters模型:

public class DTParameters
{
    public int Draw { get; set; }
    public DTColumn[] Columns { get; set; }
    public DTOrder[] Order { get; set; }
    public int Start { get; set; }
    public int Length { get; set; }
    public DTSearch Search { get; set; }
    public IEnumerable<string> AdditionalValues { get; set; }
}

我看到的大多数示例都说明要对应用程序进行调整。在Startup.cs文件的Configure调用中使用UseMVC实例化,但是我的实例却没有:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedMemoryCache();
    services.AddControllersWithViews();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticfiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

(添加)

{"draw":1,"columns":[{"data":"studentName","name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":"studentEMail",{"data":null,{"data":"finalGrade",{"data":"lastAttendDate",{"data":"bannerID",{"data":"crn","regex":false}}],"order":[{"column":0,"dir":"asc"}],"start":0,"length":10,"regex":false}}

我再次重试了我的简单参数,注意到我发送的原始ID字段是一个整数,但是当我将其设为字符串(如模型所示)时,它没有问题。

public class SimpleParam
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Foo { get; set; }
}

{"id": "1","name": "fred","foo": "bob"}

所以,这意味着我将不得不弄清楚DTParameters模型出了什么问题。

octer_liu 回答:ASP.Net Core 3.1:控制器方法始终从HttpPost调用中接收NULL参数

错误是“ dir”:“ asc”。您需要将其更改为int(“ dir”:0),或使用

装饰类属性或枚举
[JsonConverter(typeof(JsonStringEnumConverter))]

或将其放入startup.cs

public void ConfigureServices(IServiceCollection services)
{

    services
        .AddControllers()
        .AddJsonOptions(options => 
           options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())
        );

    //...
 }

您的输入已被美化:

{
    "draw": 1,"columns": [
        {
            "data": "studentName","name": "","searchable": true,"orderable": true,"search": {
                "value": "","regex": false
            }
        }
    ],"order": [
        {
            "column": 0,"dir": "asc"
        }
    ],"start": 0,"length": 10,"search": {
        "value": "","regex": false
    }
}

您的数据表类具有正确的修饰(请参见上面的DTOrderDir):

public class DTParameters
{
    public int Draw { get; set; }
    public DTColumn[] Columns { get; set; }
    public DTOrder[] Order { get; set; }
    public int Start { get; set; }
    public int Length { get; set; }
    public DTSearch Search { get; set; }
    public IEnumerable<string> AdditionalValues { get; set; }
}

public class DTColumn
{
    public string Data { get; set; }
    public string Name { get; set; }
    public bool Searchable { get; set; }
    public bool Orderable { get; set; }
    public DTSearch Search { get; set; }
}

public class DTOrder
{
    public int Column { get; set; }
    public DTOrderDir Dir { get; set; }
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum DTOrderDir
{
    ASC,DESC
}

public class DTSearch
{
    public string Value { get; set; }
    public bool Regex { get; set; }
}

在此处阅读更多信息:JavaScriptSerializer - JSON serialization of enum as string

本文链接:https://www.f2er.com/2925413.html

大家都在问