2016-06-14 100 views
3

在我的Web API我有一个文件控制器,带有两个简单动作:“的参数字典包含无效项”错误,网页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": "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

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

我在做什么错?请指教。

回答

1

你的第二个函数有一个参数name,默认参数叫做id。根据您当前的设置,您可以在

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

访问第二个功能请在网址的工作,如同你先前规定,我会建议使用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没有这样的约束,所以当参数不是整数时应该匹配。

+0

谢谢,你能解释一下为什么我还需要包含'[RoutePrefix(“api/Document”)]'? – user3378165

+1

它定义了控制器的基本路线。你可以不用,但是你需要改成'[Route(“api/Document/{id:int}”)]' - 你的选择。 – Richard

+0

完美工作,非常感谢您的明确答案! – user3378165