ASP.NET Web API中的可选查询字符串参数 [英] Optional query string parameters in ASP.NET Web API

查看:141
本文介绍了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

所有查询字符串参数都可以为null.也就是说,调用者可以指定0到5个参数中的所有参数.

All of the query string parameters can be null. That is, the caller can specify from 0 to all of the 5 parameters.

MVC4 Beta 中,我曾经做过以下事情:

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回答:

MVC4 RC doesn't behave like this anymore. If I specify fewer than 5 parameters, it replies with a 404 saying:

在与请求匹配的控制器"Books"上未找到任何动作.

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天全站免登陆