Dot-Net

WCF 和可選參數

  • April 25, 2011

我剛開始使用帶有 REST 和 UriTemplates 的 WCF。現在可以使用可選參數嗎?

如果不是,你們會建議我為一個具有三個始終在 url 中使用的參數以及其他可選(不同數量)參數的系統做什麼?

例子:

https://example.com/?id=ID&type=GameID&language=LanguageCode&mode=free 
  • id、type、language 始終存在
  • 模式是可選的

我剛剛用 WCF 4 對其進行了測試,它沒有任何問題。如果我不在查詢字元串中使用模式,我將得到 null 作為參數的值:

[ServiceContract]
public interface IService
{
   [OperationContract]
   [WebGet(UriTemplate = "GetData?data={value}&mode={mode}")]
   string GetData(string value, string mode);
}

方法實現:

public class Service : IService
{
   public string GetData(string value, string mode)
   {
       return "Hello World " + value + " " + mode ?? "";
   }
}

對我來說,看起來所有查詢字元串參數都是可選的。如果查詢字元串中不存在參數,則其類型的預設值 => nullfor string, 0 forint。MS 還指出應該實現這一點。

無論如何,您始終可以使用 和 定義UriTemplateidtype通過以下language方式訪問方法內的可選參數WebOperationContext

var mode = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["mode"];

引用自:https://stackoverflow.com/questions/5781342