【发布时间】:2016-07-18 23:23:18
【问题描述】:
Web API 未填充参数对象 在研究了许多文章(最具体地说:Complex type is getting null in a ApiController parameter 以及其他文章)之后,我得出了以下代码,用于将对象参数从 AngularJS $Resource 工厂传递到 ASP.NET Web API (C#) 控制器。 (最终搜索对象会更复杂,但为了简单起见我减少了属性的数量)
模特:
public class SearchModel
{
public long ClientId { get; set; }
public string EmployeeName { get; set; }
public string FromDate { get; set; }
public string ToDate { get; set; }
}
AngularJS 工厂
(function () {
'use strict';
angular
.module('mainApp')
.factory('searchService', searchService);
searchService.$inject = ['$resource', 'baseApiUrl'];
function searchService($resource, baseApiUrl) {
return $resource(baseApiUrl + "api/Search", null, {
query: { method: "Get", url: baseApiUrl + "api/Search/Get:searchModel", params: { searchModel: '@searchModel' }, isArray: true }
});
})
();
执行此代码时会生成此 URI:
@987654322@
请求被路由到以下 SearchController:
[RoutePrefix("api/Search")]
public class SearchController : BaseController
{
//this c’tor contains all the necessary code to implement ninject bindings etc.
public SearchController(…): base(…)
{…}
#if !DEBUG
[Authorize] //note: this allows me to execute from Fiddler w/o an auth token
#endif
[HttpGet]
[Route("{searchModel}")]
public IHttpActionResult Get([FromUri] SearchModel searchModel)
{
try
{
//Here is where I am breaking the execution to test the results:
// search model “Is” (not null) but all properties of object ARE null strings or 0 (the long)
var result = _searchQuery.Get(searchModel);
return this.GetResult(result);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
当我在上面提到的点进入中断模式时,即时窗口告诉我“请求”查询字符串按预期完成......
为什么我传递的值没有填充到控制器的 SearchModel 对象中。
[编辑:在接受答案后,我需要添加角度控制器以获得有效的解决方案]
控制者
(function () {
'use strict';
angular
.module('mainApp')
.controller('SearchController', SearchController);
SearchController.$inject = ['$filter', 'searchService'];
function SearchController($filter, searchService) {
var vm = this;
vm.searchModel = {
fromDate: "3/1/2016",
toDate: "3/30/2016",
clientId: 4,
employeeName: "Bob"
}
vm.data = searchService.query(vm.searchModel);
}})();
(请注意,“下一步”我计划使用绑定来填充这些值...但我希望轻松实现...除了日期...)
【问题讨论】:
-
我认为你不应该有
[Route("{searchModel}")]期望名称为searchModel的变量,它应该是[Route("")]才能使其工作 -
是的,它确实“期望”变量 searchModel ......这就是我想要的。 searchModel 变量确实存在......但没有像我期望的那样填充来自 URI 的值......但没有得到。
-
很抱歉再次问你,但你尝试过我的建议了吗?
-
能否尝试将对象 SearchModel 更改为动态类型,以查看接收控制器的内容是什么?因为当对象在控制器端保持为空时,因为它无法分配值。我认为这与您在查询开头使用的 /Get 有关
-
@PankajParkar,是的,只是为了确定……我知道我在这里遗漏了一些东西。如果没有该 Route 属性,请求将被拒绝并出现 500 错误。
标签: c# angularjs asp.net-web-api