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

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

未在控制器书籍"上找到与请求匹配的操作.

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