簡體   English   中英

ASP.NET Web API中的可選查詢字符串參數

[英]Optional query string parameters in ASP.NET Web API

我需要實現以下WebAPI方法:

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

所有查詢字符串參數都可以為null。 也就是說,調用者可以指定從0到所有5個參數。

MVC4 beta中我曾經做過以下事情:

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說:

未在與請求匹配的控制器“Books”上找到任何操作。

什么是正確的方法簽名,使其行為像以前一樣,而不必在URL路由中指定可選參數?

此問題已在MVC4的常規版本中得到修復。 現在你可以這樣做:

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

一切都將開箱即用。

如vijay建議的那樣,可以將多個參數作為單個模型傳遞。 當您使用FromUri參數屬性時,這適用於GET。 這告訴WebAPI從查詢參數中填充模型。

結果是只有一個參數的清潔控制器動作。 有關詳細信息,請參閱: 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; }
  }

它甚至支持多個參數,只要屬性不沖突即可。

// 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; }
}

更新
為了確保值是可選的,請確保對模型屬性使用引用類型或nullables(例如int?)。

對所有參數使用初始默認值,如下所示

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

如果要傳遞多個參數,則可以創建模型而不是傳遞多個參數。

如果你不想傳遞任何參數,那么你也可以跳過它,你的代碼看起來整潔干凈。

無法為未聲明為“ optional ”的參數提供默認值

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

在您的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} _
      )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM