ASP.NET MVC 4 Web API中如何使用FromBody参数进行数据绑定?
- 内容介绍
- 文章标签
- 相关推荐
本文共计283个文字,预计阅读时间需要2分钟。
我有点困扰。我有一个控制器(派生自ApiController)具有以下方法:csharp[ActionName(getusername)]public string GetUserName(string name){ return TestUser;}我的路由配置如下:csharpconfig.Routes.MapHttpRoute(name: ActionA);
我有点困惑.我有一个控制器(派生自ApiController)具有以下方法:[ActionName("getusername")] public string GetUserName(string name) { return "TestUser"; }
我的路由设置如下:
config.Routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
当我尝试在fiddler中使用GET命中/ api / mycontroller / getusername / test时,我一直收到400错误.
当我将[FromBody]添加到GetUserName中的name参数时,我发现一切正常.
我在某种程度上认为[FromBody]用于HttpPost,表明该参数位于帖子的主体中,因此不需要GET.看起来我错了.
这是如何运作的?
您需要将路由更改为:config.Routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{name}", defaults: new { name = RouteParameter.Optional } );
或将参数名称更改为:
[ActionName("getusername")] public string GetUserName(string id) { return "TestUser"; }
注意:其他路由参数必须与方法参数名称匹配.
本文共计283个文字,预计阅读时间需要2分钟。
我有点困扰。我有一个控制器(派生自ApiController)具有以下方法:csharp[ActionName(getusername)]public string GetUserName(string name){ return TestUser;}我的路由配置如下:csharpconfig.Routes.MapHttpRoute(name: ActionA);
我有点困惑.我有一个控制器(派生自ApiController)具有以下方法:[ActionName("getusername")] public string GetUserName(string name) { return "TestUser"; }
我的路由设置如下:
config.Routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
当我尝试在fiddler中使用GET命中/ api / mycontroller / getusername / test时,我一直收到400错误.
当我将[FromBody]添加到GetUserName中的name参数时,我发现一切正常.
我在某种程度上认为[FromBody]用于HttpPost,表明该参数位于帖子的主体中,因此不需要GET.看起来我错了.
这是如何运作的?
您需要将路由更改为:config.Routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{name}", defaults: new { name = RouteParameter.Optional } );
或将参数名称更改为:
[ActionName("getusername")] public string GetUserName(string id) { return "TestUser"; }
注意:其他路由参数必须与方法参数名称匹配.

