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

查看:35
本文介绍了为什么我们必须指定 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 调用控制器上的方法时,它必须为参数设置值,这个过程称为参数绑定.

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、decimal 和 string,以及任何带有可从字符串转换的类型转换器的类型.

  • 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.

很多 更多 信息 如果您在 google 上搜索web api 参数绑定".

There is a lot more information on the web if you google "web api parameter binding".

这篇关于为什么我们必须指定 FromBody 和 FromUri?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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