C# ASP.NET Web API 中的可选查询字符串参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11862069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:32:55  来源:igfitidea点击:

Optional query string parameters in ASP.NET Web API

c#urlasp.net-web-apiquery-string

提问by frapontillo

I need to implement the following WebAPI method:

我需要实现以下 WebAPI 方法:

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

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

所有查询字符串参数都可以为空。也就是说,调用者可以指定从 0 到所有 5 个参数。

In MVC4 betaI used to do the following:

MVC4 测试版中,我曾经执行以下操作:

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 doesn't behave like this anymore. If I specify fewer than 5 parameters, it replies with a 404saying:

MVC4 RC 不再像这样。如果我指定的参数少于 5 个,它会回复一个404说法:

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

在控制器“书籍”上找不到与请求匹配的操作。

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?

什么是正确的方法签名,使其表现得像以前一样,而不必在 URL 路由中指定可选参数?

采纳答案by frapontillo

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

此问题已在 MVC4 的常规版本中修复。现在你可以这样做:

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

and everything will work out of the box.

一切都将开箱即用。

回答by Muhammad Amin

Use initial default values for all parameters like below

对所有参数使用初始默认值,如下所示

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

回答by vijay

if you want to pass multiple parameters then you can create model instead of passing multiple parameters.

如果要传递多个参数,则可以创建模型而不是传递多个参数。

in case you dont want to pass any parameter then you can skip as well in it, and your code will look neat and clean.

如果你不想传递任何参数,那么你也可以跳过它,你的代码看起来整洁干净。

回答by Rizwan Mumtaz

Default values cannot be supplied for parameters that are not declared 'optional'

无法为未声明为“ optional”的参数提供默认值

 Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)

In your WebApiConfig

在你的 WebApiConfig

 config.Routes.MapHttpRoute( _
          name:="books", _
          routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
          defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
      )

回答by Andrew C

It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.

正如 vijay 建议的那样,可以将多个参数作为单个模型传递。当您使用 FromUri 参数属性时,这适用于 GET。这告诉 WebAPI 从查询参数填充模型。

The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

结果是一个更清晰的控制器动作,只有一个参数。有关更多信息,请参阅:http: //www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

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

  public class BookQuery
  {
    public string Author { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public string SomethingElse { get; set; }
    public DateTime? Date { get; set; }
  }

It even supports multiple parameters, as long as the properties don't conflict.

它甚至支持多个参数,只要属性不冲突。

// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
  // ...
}

public class Paging
{
  public string Sort { get; set; }
  public int Skip { get; set; }
  public int Take { get; set; }
}

Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.

更新
为了确保这些值是可选的,请确保对模型属性使用引用类型或可空值(例如 int?)。