2015-11-01 90 views
0

獲取請求來自SMS API傳送報告以獲取有關SMS的信息。是否可以在變量名.net Web API中使用破折號字符?

將會發布到我的api的變量之一是:?err-code = 0。是否可以在.Net Web API解決方案中完成,還是應該使用其他語言?

的Web API獲取方法:

public HttpResponseMessage Get([FromUri]TestModel testingDetials) 
    {   

     return Request.CreateResponse(System.Net.HttpStatusCode.OK); 
    } 

型號

public class TestModel 
    { 
     public string foo { get; set; } 

     public string err_code { get;set; } 
    } 

我想在這個網站他們沒有發現的各種解決方案,如添加[JsonProperty]和[的DataMember]將err_code物業工作。

+1

所以你設置[JsonProperty(屬性名= 「ERR-代碼」)?其Web API版本2? –

+0

是的,我所做的也是它的Web API版本2.我是否需要添加一些設置或附加代碼來使其工作? – Thinker

+0

我本來期待它的工作。 foo綁定?你可以做一個自定義模型聯編程序? –

回答

1

您可以使用[JsonProperty(PropertyName = "err-code")]提供的請求正在接收爲JSON。這是因爲JsonProperty是Newtonsoft JSON序列化程序庫的一部分,這是Web API用於反序列化JSON的內容。如果請求不是JSON,則該庫不在管道中使用。

正如你所提到的,你可以使用HttpContext。如果我沒有記錯,MVC中的模型綁定將' - '轉換爲'_',但我可能是錯的。無論如何,我推薦使用強類型模型來使用模型綁定。這基本上是編寫http上下文和模型之間的自定義映射。你甚至可以通過編寫一個基於約定的規則來擴展通常的一個,並將諸如「err-code」之類的東西自動映射到名爲ErrCode的屬性。這裏是一個例子,滾動一下:http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api 快樂編碼! (通過我會提供一個完整的答案,爲...以及... ...有一個完整的答案)

1

對於我的情況,我創建了一個模型聯編程序,將var「_」轉換爲「 - 」並設置通過使用反射的值。這個答案僅供參考。 下面是代碼:(此解決方案用於Web API不MVC)

public class SmsReceiptModelBinder : IModelBinder 
{ 

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType != typeof(SmsReceiptModel)) 
     { 
      return false; 
     } 


     Type t = typeof(SmsReceiptModel); 

     var smsDetails = new SmsReceiptModel(); 
     foreach (var prop in t.GetProperties()) 
     { 
      string propName = prop.Name.Replace('_', '-'); 
      var currVal = bindingContext.ValueProvider.GetValue(
        propName); 
      if (currVal != null) 
       prop.SetValue(smsDetails, Convert.ChangeType(currVal.RawValue, prop.PropertyType), null); 
     } 

     bindingContext.Model = smsDetails; 
     return true; 

    } 

} 
相關問題