WebApiConfig&路线之间有什么区别

时间:2016-10-29 11:13:55

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

我有一个实现两个Get方法的WebApiController:一个不需要参数,另一个方法需要一个interger参数......

//Get api/<controller>
    public IEnumerable<EmployeeVM> Get()
    {
        List<EmployeeVM> list = new List<EmployeeVM>()
        {
            new EmployeeVM(){
                FullName = "Milton Waddams"
            },
        new EmployeeVM(){
                FullName = "Andy Bernard"
            }
        };
        return list;
    }

    //Get api/<controller>
    public string Get(int id)
    {
        return "value";
    }

如果我在WebApiConfig类中使用以下配置,

configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });

然后我会收到以下错误:

  

“参数字典包含参数'id'的空条目   方法'System.String Get(Int32)'的非可空类型'System.Int32'   在'AngularForMVC.Controllers.EmployeeWebApiController'中。可选的   参数必须是引用类型,可空类型或声明为   一个可选参数。“

现在,如果我使用以下配置:

configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });

然后它的工作原理。我可以执行Get()方法而不会出现任何错误。

有什么区别?为什么第二个代码引用有效?我知道我在网址路径中添加了{action},但即使我没有在网址中加入{action}路径,这仍然有用。

3 个答案:

答案 0 :(得分:0)

您应该将id参数作为可空int。获取(int?id)

答案 1 :(得分:0)

我总是更喜欢使用[Route]属性来定义路由配置,而不是在route.config中添加新角色

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

答案 2 :(得分:0)

由于多种原因,自定义[Route]会更好

1 - 确定每个GET请求应该做什么。 例如,如果您有[Route("api/getlist")][Route("api/getitem/{id}")] 这将更具描述性。

2 - 你不会面对你现在面临的问题。