在ASP.NET的Web API可选参数 [英] Optional parameters in ASP.NET Web API

查看:107
本文介绍了在ASP.NET的Web API可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现以下的WebAPI方式:

I need to implement the following WebAPI method:

/api/books?author=XXX&title=XXX&isbn=XXX&somethingelse=XXX&date=XXX

所有的参数可以为空,即调用者可以指定0到所有5个参数。

All of the parameters can be null, i.e. the caller can specify from 0 to all the 5 parameters.

MVC4测试版我以前做到以下几点:

In MVC4 beta I used to do the following:

public class BooksController : ApiController
{
    // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
    public string GetFindBooks(string author, string title, string isbn, string somethingelse, DateTime? date) 
    {
        // ...
    }
}

MVC4 RC没有这样的表现了。如果我指定少于5个参数,它与一个答复 404

没有行动上的控制器图书与请求匹配找到。

No action was found on the controller 'Books' that matches the request.

什么是正确的方法签名,使其行为像以前那样,而不需要在URL路由到指定可选参数?

What is the correct method signature to make it behave like it used to, without having to specify the optional parameter in the URL routing?

推荐答案

此问题已被固定在MVC4的定期发布。
现在,你可以这样做:

This issue has been fixed in the regular release of MVC4. Now you can do:

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

和一切都会开箱即用。

这篇关于在ASP.NET的Web API可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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