简体   繁体   English

通过ID使用可选参数获取

[英]GET by Id With Optional Parameters

In an ASP.NET Web API I have modified the default GET action to accept an optional parameter which will declare the depth at which to get the Object: 在ASP.NET Web API中,我修改了默认的GET操作以接受可选参数,该参数将声明获取对象的深度:

    public ObjectModel Get(int id, int? loadType = 1)
    {
        if (loadType.Value == 1)
        {
            return GetDeepObjectModel(id);
        }
        else
        {
            return GetShallowObjectModel(id);
        }
    }

Given the default route: 给定默认路由:

    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"\d+" }
        );

I have an issue with valid requests in that: 我的有效要求有一个问题:

    https://www.mysite.com/api/objects/1234?loadType=1

will work, but I would also like this same action to work for the basic get - considering the loadType param as optional: 会起作用,但我也希望对基本get可以执行相同的操作-将loadType参数视为可选:

    https://www.mysite.com/api/objects/1234

With the second request, I get a 404 not found. 与第二个请求,我得到404未找到。 It seems that the id is not getting counted as a matched variable when it is paired with an optional param. 将该ID与可选参数配对时,似乎没有将其计为匹配变量。

Is there something I am missing here? 我在这里缺少什么吗? I would very much not to start adding new routes to cover this issue, since my experience with MVC has told me that adding routes can get out of hand very quickly. 因为我在MVC方面的经验告诉我,添加路由可以很快地失控,所以我非常不会开始添加新路由来解决此问题。

I can't be entirely sure of this, but it seems the default value on my 我不能完全确定这一点,但似乎我的默认值

    int? loadType = 1

parameter is causing the issue. 参数导致了问题。 If I change the default value to null 如果我将默认值更改为null

    int? loadType = null

And check in the action for setting the default value 并检查设置默认值的操作

    if (!loadType.HasValue)
    {
        loadType = 1;
    }

both versions of the request are properly directed to the intended action. 请求的两个版本都正确地定向到了预期的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM