【问题标题】:ASP.Net Core 3 and simple POST the controllerASP.Net Core 3 和简单的 POST 控制器
【发布时间】:2020-02-14 19:24:15
【问题描述】:

我正在尝试 POST 到 ASP.NET core 3 服务器。 但是我的number 始终是0。 ASP.Net Core 3 有没有我看不懂的技巧?

参数[FromBody]没有解决问题。并且作为参数的类没有帮助,值不会改变。

[HttpPost]
[Route("/api/add")]
public ActionResult<Dictionary<string, object>> Add(int number)
{

    // number is always 0 :(  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    number += 1;

    var d = new Dictionary<string, object>
    {
        ["message"] = "Hello",
        ["number"] = number 
    };

    return Ok(d);
}
let input = { number: 5825 }

$.ajax(
    {
        url: `/api/add`,
        type: 'POST',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(input),
        accepts: "application/json",
        complete: function (output) {
            // completed
        }
    }
);

我的服务是

services.AddSession();
services.AddHttpContextAccessor();
services.AddControllersWithViews();

我用

app.UseSession();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Default}/{action=Index}/{id?}"); });

【问题讨论】:

  • let input = { number: 0 } 您将其设置为 0。
  • 是的,抱歉,我忘记更改号码了。但显然这并不能解决问题(:
  • 发布复杂类型以绑定到简单类型。

标签: javascript c# asp.net-core asp.net-core-3.0


【解决方案1】:

根据显示的客户端代码,该客户端正在发布复杂类型以绑定到服务器上的简单类型。

创建模型

public class Data {
    public int number { get; set; }
}

将模型绑定到动作

[HttpPost]
[Route("/api/add")]
public IActionResult Add([FromBody]Data model) {

    if(ModelState.IsValid) {

        var number = model.number;
        number += 1;

        var d = new {
            message = "Hello",
            number = number 
        };

        return Ok(d);
    }

    return BadRequest(ModelState);
}

【讨论】:

    【解决方案2】:

    在您的 javascript 中,不要发布对象输入,而是尝试直接发布数字变量:

    let number=5825;
    
    $.ajax(
        {
            url: `/api/add`,
            type: 'POST',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: number,
            accepts: "application/json",
            complete: function (output) {
                // completed
            }
        }
    );
    

    在您的控制器中使用 [FromBody] 注释:

    [HttpPost]
    [Route("/api/add")]
    public ActionResult<Dictionary<string, object>> Add([FromBody]int number)
    {
    
        // number is always 0 :(  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    
        number += 1;
    
        var d = new Dictionary<string, object>
        {
            ["message"] = "Hello",
            ["number"] = number 
        };
    
        return Ok(d);
    }
    

    我同意问题是您尝试发送复杂类型,而您的操作仅接受简单类型 int。如果您仍有问题,请告诉我。

    【讨论】:

      【解决方案3】:

      您可以按照@Nkosi 的解决方案将属性添加到模型。或者,如果您不想创建模型,只需将数字添加到 url 查询,如下所示:

      let number = 5825;
          $.ajax(
              {
                  url: '/api/add?number=' + number,
                  type: 'POST',
                  dataType: "json",
                  contentType: "application/json; charset=utf-8",
                  accepts: "application/json",
                  complete: function (output) {
                      // completed
                  }
              }
          );
      
      
      [HttpPost]
      [Route("/api/add")]
      
      public ActionResult<Dictionary<string, object>> Add(int number)
      {
        //...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-09
        • 2019-04-15
        • 2012-08-27
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 2021-02-09
        • 2019-12-31
        相关资源
        最近更新 更多