【问题标题】:'The parameters dictionary contains a null entry' error, Web API“参数字典包含一个空条目”错误,Web API
【发布时间】:2016-10-14 23:31:46
【问题描述】:

在我的 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

但是这个网址(应该执行第二个功能):

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 }
        );

我做错了什么?请指教。

【问题讨论】:

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


    【解决方案1】:

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

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

    要使 URL 像您之前指定的那样工作,我建议使用 attribute routingroute 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 没有这样的约束,所以当参数不是整数时应该匹配。

    【讨论】:

    • 谢谢,你能解释一下为什么我还需要包含[RoutePrefix("api/Document")]吗?
    • 这定义了控制器的基本路由。您可以忽略它,但您需要更改为 [Route("api/Document/{id:int}")] - 您的选择。
    • 完美运行,非常感谢您的明确回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多