且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Web API中的[FromRoute]和[FromBody]有什么区别?

更新时间:2023-02-15 23:12:13

FromBody

指定应使用请求正文来绑定参数或属性.

FromBody

Specifies that a parameter or property should be bound using the request body.

使用 FromBody 属性时,您指定的数据是来自请求正文的主体,而不是来自请求URL/URI.您不能将此属性与 HttpGet 请求一起使用,而只能与PUT,POST和Delete请求一起使用.另外,您在Web API中每个操作方法只能使用一个 FromBody 属性标记(如果mvc核心中的此方法已更改,我将找不到任何支持该标记的属性).

When you use FromBody attribute you are specifying that the data is coming from the body of the request body and not from the request URL/URI. You cannot use this attribute with HttpGet requests, only with PUT,POST,and Delete requests. Also you can only use one FromBody attribute tag per action method in Web API (if this has changed in mvc core I could not find anything to support that).

FromRouteAttribute

摘要:指定应该使用当前请求中的路由数据来绑定参数或属性.

FromRouteAttribute

Summary: Specifies that a parameter or property should be bound using route-data from the current request.

基本上,它 FromRoute 会查看您的路由参数,并根据该参数提取/绑定数据.路由在外部调用时通常基于URL.在以前版本的Web api中,这与 FromUri 类似.

Essentially it FromRoute will look at your route parameters and extract / bind the data based on that. As the route, when called externally, is usually based on the URL. In previous version(s) of web api this is comparable to FromUri.

[HttpGet("{facilityId}", Name = "GetTotalBandwidth")]
public IActionResult GetTotalBandwidth([FromRoute] int facilityId)

因此,这将尝试基于具有相同名称的route参数绑定 facilityId .

So this would try to bind facilityId based on the route parameter with the same name.

Complete route definition: /api/Settings/GetTotalBandwidth/{facilityId}
Complete received url: /api/Settings/GetTotalBandwidth/100


编辑

根据您的最后一个问题,以下是相应的代码,假设您希望将163绑定到facilityId,将10绑定到bandwidthChange参数.


Edit

Based on your last question, here is the corresponding code assuming you want 163 to be bound to facilityId and 10 to bandwidthChange parameters.

// PUT: api/Setting/163/10

[HttpPut("{facilityId}/{bandwidthChange}")] // constructor takes a template as parameter
public void UpdateBandwidthChangeHangup([FromRoute] int facilityId, [FromRoute] int bandwidthChange) // use multiple FromRoute attributes, one for each parameter you are expecting to be bound from the routing data
{
    _settingRespository.UpdateBandwidthHangup(facilityId, bandwidthChange);
}

如果其中一个参数包含一个复杂的对象,并且希望将其作为Http Request的主体发送,则可以使用 FromBody 代替 FromRoute 该参数.这是从使用ASP构建第一个Web API的示例.NET Core MVC

If you had a complex object in one of the parameters and you wanted to send this as the body of the Http Request then you could use FromBody instead of FromRoute on that parameter. Here is an example taken from the Building Your First Web API with ASP.NET Core MVC

[HttpPut("{id}")]
public IActionResult Update([FromRoute] string id, [FromBody] TodoItem item);

MVC Core中还有其他选项,例如 FromHeader FromForm FromQuery .

There are also other options in MVC Core like FromHeader and FromForm and FromQuery.