为什么我们必须指定FromBody和FromUri? [英] Why do we have to specify FromBody and FromUri?

查看:162
本文介绍了为什么我们必须指定FromBody和FromUri?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么ASP.NET Web API中需要FromBodyFromUri属性?

Why are the FromBody and FromUri attributes needed in ASP.NET Web API`?

使用属性与不使用属性有什么区别?

What are the differences between using the attributes and not using them?

推荐答案

当ASP.NET Web API调用控制器上的方法时,它必须为参数设置值,该过程称为 parameter binding >.

When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.

默认情况下,Web API使用以下规则来绑定参数:

By default, Web API uses the following rules to bind parameters:

  • 如果参数是简单"类型,则Web API会尝试从URI中获取值 .简单类型包括.NET基本类型(int,bool,double等),以及TimeSpan,DateTime,Guid,十进制和字符串,以及带有可从字符串转换的类型转换器的任何类型.

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.

对于复杂类型,Web API尝试使用媒体类型格式化程序从消息正文中读取值 .

For complex types, Web API tries to read the value from the message body, using a media-type formatter.

因此,如果要覆盖上述默认行为并强制Web API从URI读取复杂类型,请在参数中添加[FromUri]属性.要强制Web API从请求正文中读取简单类型,请在参数中添加[FromBody]属性.

So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

因此,要回答您的问题,Web API中对[FromBody][FromUri]属性的需要只是在必要时覆盖上述默认行为.请注意,您可以将两种属性都用于控制器方法,但只能用于不同的参数,如

So, to answer your question, the need of the [FromBody] and [FromUri] attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆