'参数字典包含空条目&错误,Web API

人气:431 发布:2022-10-16 标签: c# asp.net-web-api asp.net-web-api2

问题描述

在我的Web API上,我有一个带有两个简单操作的文档控制器:

[AllowAnonymous]
public class DocumentController : ApiController
{    
    public String Get(int id)
    {
        return "test";
    }

    public String Get(string name)
    {
        return "test2";
    }
}

以下URL(执行第一个函数)运行正常:

http://localhost:1895/API/Document/5

但此URL(应执行第二个函数):

http://localhost:1895/API/Document/test

引发此错误:

{ "Message":"请求无效。", "MessageDetail":"对于‘API.Controllers.DocumentController’中的方法‘xx.yy.Document Get(Int32)’,参数字典包含不可为空类型‘System.Int32’的参数‘id’的空条目。可选参数必须是引用类型、可为空类型或声明为可选参数。" )

这是WebApiConfig:

中的MapHttpRoute
 config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

我做错了什么?请提供建议。

推荐答案

您的第二个函数有一个参数name,默认参数称为id。使用您当前的设置,您可以访问

上的第二个功能

http://localhost:1895/API/Document/?name=test

要使URL按照您先前指定的方式工作,我建议使用attribute routing和route constraints。

启用属性路由:

config.MapHttpAttributeRoutes();

在您的方法上定义路由:

[RoutePrefix("api/Document")]
public class DocumentController : ApiController
{    
    [Route("{id:int}")]
    [HttpGet]
    public String GetById(int id)   // The name of this function can be anything now
    {
        return "test";
    }

    [Route("{name}"]
    [HttpGet]
    public String GetByName(string name)
    {
        return "test2";
    }
}
在本例中,GetById对路径({id:int})有一个约束,该约束指定参数必须为整数。GetByName没有这样的约束,因此当参数不是整数时应该匹配。

709