使用带有可选参数的[Route]属性调用Web API 2.0操作会返回404未找到?

时间:2014-10-28 15:52:18

标签: c# asp.net-mvc asp.net-web-api2

尝试使用this article在Web API 2.0项目中创建参数可选 - 基本上使用问号语法使其成为可选项。但是当省略参数时,该动作是不可达的(404)。

通话格式:

/lists/departments : returns 404
/lists/departments/sometype : works

动作:

[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type)
{
    //this action is not being reached
}

this SO post所示更改gloabal.asax.cs中注册路由的顺序没有帮助。

的global.asax.cs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        //WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

2 个答案:

答案 0 :(得分:3)

尝试使用C#术语为type参数指定默认值。像这样:

[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type = null)
{
    //this action is not being reached
}

答案 1 :(得分:1)

如文档中所述,您需要为类型

提供默认值

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#optional

&#34;如果路由参数是可选的,则必须为method参数定义默认值。&#34;

这应该有效

[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type = null)
{
    //this action is not being reached
}