2016-03-12 143 views
3

我想通過多個參數傳遞給一個httpget web api函數。我遇到的關鍵問題是空查詢字符串參數正在轉換爲空。web api空查詢字符串參數

我可以通過創建類似下面的東西一類解決這個問題:

public class CuttingParams 
{ 
    [DisplayFormat(ConvertEmptyStringToNull = false)] 
    public string batch_number { get; set; } 
    [DisplayFormat(ConvertEmptyStringToNull = false)] 
    public string filter { get; set; } 
    [DisplayFormat(ConvertEmptyStringToNull = false)] 
    public string initiation_month { get; set; } 
    [DisplayFormat(ConvertEmptyStringToNull = false)] 
    public string initiation_year { get; set; } 
} 

但我絕對受詛咒討厭不必創建一個類爲一次使用過的想法。

我已經做了大量的研究,並且非常努力地找到一種方法來改變上面以外的默認行爲。我真的只是想做到這一點:

[HttpGet] 
    public object Search(string batch_number, string filter, string initiation_month, string initiation_year) 
    { 
    } 

我失去了一個容易的方式來改變這種默認行爲,或者我應該尋找到我的教學貫徹自己的查詢字符串解析器,我可以在全局範圍?

感謝

更新

似乎有關於我的文章有些混亂,對不起,如果我不清楚。我會盡力澄清。

我想只傳遞簡單的基本類型到我的HttpGet方法,如第二個代碼片段所示。我遇到的問題是空字符串參數將被轉換爲空。

ie. this url: http://localhost/api/cutting/search?batch_number=&filter=&intiation_month=Jan&initiation_year=2016 

會產生以下值在API:

batch_number = null 
filter = null 
initiation_month = Jan 
initiation_year = 2016 

如果我改變了搜索功能,使用類的第一個代碼段,它會工作,我想,但我真的努力避免長期使用類參數。

+0

我想了解您預期的結果。在你的例子中,是否你想要的是參數沒有被綁定,它們被設置爲空字符串而不是'null'? – Nkosi

+0

你嘗試過'DefaultValueAttribute'嗎?例如:'[DefaultValue(「」)] public string initiation_year {get;組; }' –

+0

@Nkosi我後來的是,參數設置爲精確的,我傳入,即。如果我傳入一個空字符串,我希望它是一個空字符串,此刻,如果我傳入一個空字符串,參數值將爲空 – crazyhor77

回答

0

好吧,我按照自己想要的方式工作。我不得不適應一些類似的代碼,我找到了一個mvc web api,但使它簡單得多。按照如下所示創建自定義模型聯編程序並將其添加到全局配置中。希望這可以幫助別人。

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     // Web API configuration and services 
     GlobalConfiguration.Configuration.BindParameter(typeof(string), new EmptyStringModelBinder()); 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{action}" 
     ); 
    } 
} 

public class EmptyStringModelBinder : System.Web.Http.ModelBinding.IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext) 
    { 
     string val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue; 
     bindingContext.Model = val; 

     return true; 
    } 
} 
0

我相信這是設計。如果ModelBinder無法映射該參數,它將恢復爲該參數的默認類型。

,如果它是一個簡單的值類型一樣int哪裏會該值設置爲0

同樣會發生看一看下面的文章,看看它是否能幫助你

Parameter Binding in ASP.NET Web API

+0

它是由設計。我不想要默認行爲。我知道你可以創建自定義的格式化程序等來覆蓋web api行爲,但我不知道該怎麼看才能嘗試並重寫此默認行爲,將僅當使用基本類型作爲參數時將空字符串參數更改爲null – crazyhor77

相關問題