Web API“参数字典包含空条目"错误 [英] 'The parameters dictionary contains a null entry' error, Web API

查看:251
本文介绍了Web API“参数字典包含空条目"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On my Web API I have a Document Controller with two simple actions:

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

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

以下URL(执行第一个功能)可以正常工作:

The following URL (executes the first function) works fine:

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

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

But this URL (should execute the second function):

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

引发此错误:

{ "message":请求无效.", "messageDetail":参数字典为'API.Controllers.DocumentController'中的方法'xx.yy.Document Get(Int32)'包含一个非空类型'System.Int32'的参数'id'的空条目.可选参数必须是引用类型,可为null的类型,或者必须声明为可选参数." }

{ "message": "The request is invalid.", "messageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'xx.yy.Document Get(Int32)' in 'API.Controllers.DocumentController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter." }

这是WebApiConfig中的MapHttpRoute:

This is the MapHttpRoute in the WebApiConfig:

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

我做错了什么?请告知.

What am I doing wrong? Please advise.

推荐答案

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

Your second function has a parameter name, and the default parameter is called id. With your current setup, you can access the second function on

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

要使URL按您之前指定的方式工作,我建议使用

To make the URLs work as you have specified previously, I would suggest using attribute routing and route constraints.

启用属性路由:

config.MapHttpAttributeRoutes();

在您的方法上定义路由:

Define routes on your methods:

[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没有这样的约束,因此当参数不是整数时应该匹配.

In this example, GetById has a constraint on the route ({id:int}) which specifies that the parameter must be an integer. GetByName has no such constraint so should match when the parameter is NOT an integer.

这篇关于Web API“参数字典包含空条目"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆