带有空参数的 $http.get 没有访问 Web API 控制器

$http.get with null parameters are not hitting the Web API controller

我正尝试在 angular 应用程序中使用 $http.get 访问 Web API GET 控制器,如下所示:

$http.get(BasePath + '/api/documentapi/GetDocuments/' , 
                                {
                                    params: {
                                        PrimaryID: ID1,
                                        AlternateID: ID2,                                            
                                    }
                                }).then( ...

在我的例子中,PrimaryID 或 AlternateID 将具有值。因此,其中之一将始终为空。

我的网站api方法是

public DocumentsDto[] GetDocuments(decimal? PrimaryID, decimal? AlternateID)
    { ...

当其中一个值为null时,$http.get生成的url如下:

http://BaseServerPath/api/documentapi/GetDocuments/?PrimaryID=1688 

 http://BaseServerPath/api/documentapi/GetDocuments/?AlternateID=154

这不符合我的 Web API 方法。

但是如果我使用

http://BaseServerPath/api/documentapi/GetDocuments/?PrimaryID=1688&AlternateID=null

有效。我可以在我的参数中将值硬编码为 null,但是我想知道是否有任何正确的方法来实现这一点。

谢谢, 山姆

虽然您已经在 Web API 控制器上指定这两个参数可以为空,但 ASP.NET 路由引擎仍会在对该方法的调用中查找两个参数 - 即使如果其中之一为空。

理想情况下,您会创建两种方法,一种只采用主要方法,另一种采用次要方法,但在您的情况下,这有点棘手,因为您的两个 ID 属于同一类型。尽管您可以指定哪个参数对应于查询字符串中提供的值,但是这两种方法在您的控制器中将具有相同的签名(decimal 类型的单个参数)class.

所以你在这里有两个选择。要么创建新的控制器,这样你就有一个接收 PrimaryID 的查询,一个接收 SecondaryID 的查询,或者你有一个方法将包含一个 ID 的对象设置为一个值,另一个为 null, 运行 你的查询基于此。

另一种选择是将请求参数转换为复杂对象并使用 [FromUri] 从 Url 创建对象。

我从@RobJ 那里得到了正确答案。他对答案发布了 link。我也在这里粘贴相同的答案。解决方案是为 Web API 参数设置默认值。

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

在我的例子中是

public DocumentsDto[] GetDocuments(decimal? PrimaryID = null, decimal? AlternateID = null)
{ ...

你可以试试这个:

$http.get(BasePath + '/api/documentapi/GetDocuments/' , 
                            {
                                params: {
                                    PrimaryID: ID1!=undefined?ID1:0,
                                    AlternateID: ID2!=undefined?ID2:0,                                            
                                }
                            }).then( ...

那么你可以在 webapi 中处理 0...