当前位置:首页 > 后端 > .net > 正文内容

WebAPI 为什么你的[FromBody]参数总是为NULL

放牧的风6年前 (2018-04-10).net931

出于某种原因,我总是忘记Web API参数绑定的工作原理。无数次,我的[FromBody]参数为NULL。

有时间整理一下并写下来,防止以后再犯同样的错误。

大家可以阅读关于Web API中参数绑定的官方文档 parameter-binding-in-aspnet-web-api

言归正传,这是我最初的请求,测试时不起作用:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "api/discount/saveEmailForDiscount",
    data: {email: "some@email.com"}
});

C#代码如下:

[HttpPost, Route("api/discount/saveEmail")]
public IHttpActionResult SaveEmailForDiscount([FromBody] string email)  
{    
    //do something with e-mail
    return Ok(email);
}

要强制Web API从请求主体读取“简单”类型,您需要将[FromBody]属性添加到参数中。

 

Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

Web API最多只读取一次响应主体,因此只有一个操作参数可以来自请求主体。如果您需要从请求主体获取多个值,请定义一个复杂类型。


但email的值仍然是NULL。

JavaScript代码是我们使用的通用方法的一部分,所以这就是内容类型设置为application/json; charset=utf-8。虽然上面提到的文章中的例子也使用了内容类型application/json,但这是我们问题的根源。

AJAX请求的默认内容类型是application/x-www-form-urlencoded; charset=UTF-8。所以,如果我们不设定内容类型,或指定它为pplication/x-www-form-urlencoded; charset=UTF-8,它应该是正确的?

呃...不,显然这个值应该像这样格式化:

=value

知道这会产生最终的JavaScript代码:

$.ajax({
   type: "POST",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", //this could be left out as it is the default content-type of an AJAX request
    url: "api/discount/saveEmailForDiscount",
    data: =+"some@email.com"
});

最后要提到的是Asp.Net网站上的评论:

Before sending a simple type, consider wrapping the value in a complex type instead. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.

在发送简单类型之前,请考虑将值包装在复杂类型中。这为您提供了服务器端模型验证的好处,并且可以在需要时扩展模型

 


扫描二维码推送至手机访问。

版权声明:本文由放牧的风发布,如需转载请注明出处。

本文链接:https://grazingwind.com/post/14.html

分享给朋友:

相关文章

5天玩转C#并行和多线程编程系列

5天玩转C#并行和多线程编程系列

5天玩转C#并行和多线程编程系列文章目录5天玩转C#并行和多线程编程 —— 第一天 认识Parallel5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq5天玩转C#并行和多线程编程 —— 第三天 认识和使用Task5天玩转C...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。