2017-09-26 66 views
1

我正在使用Postman來調用Get。在URL我有其中的underscore可選參數。我想通過使用DataContract將這些值分配給class,但我無法做到這一點。如果我單獨閱讀它們,那就沒有問題了。在Web API中映射可選參數C#

這對我來說是新的,因此探索什麼是最好的方法來做到這一點。找到一些鏈接,建議去個別參數,但要確保我在這裏沒有丟失任何東西。

電話:http://{{url}}/Host?host_name=Test&host_zipcode=123&host_id=123

工作:如果我讀他們作爲一個單獨的參數我可以讀取這些參數值。

[HttpGet] 
[Route("api/Host")] 
public async Task<HostResponse> GetHostInfo([FromUri (Name = "host_name")] string hostName, [FromUri (Name = "host_zipcode")] string hostZipCode, [FromUri(Name = "host_id")] string hostId) 
{ 
} 

不工作:當我嘗試使用DataContract使用class,我無法閱讀。

[HttpGet] 
[Route("api/Host")] 
public async Task<HostResponse> GetHostInfo([FromUri] HostInfo hostInfo) 
{ 
} 

[DataContract] 
public class HostInfo 
{ 
    [DataMember(Name = "host_name")] 
    public string HostName { get; set; } 

    [DataMember(Name = "host_zipcode")] 
    public string HostZipCode { get; set; } 

    [DataMember(Name = "host_id")] 
    public string HostId { get; set; } 
} 

我也試過:

public class DeliveryManagerStatus 
{ 
    [JsonProperty(PropertyName = "country")] 
    public string Country { get; set; } 

    [JsonProperty(PropertyName = "delivery_provider")] 
    public string DeliveryProvider { get; set; } 

    [JsonProperty(PropertyName = "job_id")] 
    public string JobId { get; set; } 
} 

我如何分配這些屬性的一類?

回答

1

您可以使用IModelBinderdetails)實現來解析它。這是一個基於DataMember例如(從數據成員的屬性需要的鍵名):

public class DataMemberBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     var props = bindingContext.ModelType.GetProperties(); 
     var result = Activator.CreateInstance(bindingContext.ModelType); 
     foreach (var property in props) 
     { 
      try 
      { 
       var attributes = property.GetCustomAttributes(typeof(DataMemberAttribute), true); 
       var key = attributes.Length > 0 
        ? ((DataMemberAttribute)attributes[0]).Name 
        : property.Name; 
       if (bindingContext.ValueProvider.ContainsPrefix(key)) 
       { 
        var value = bindingContext.ValueProvider.GetValue(key).ConvertTo(property.PropertyType); 
        property.SetValue(result, value); 
       } 
      } 
      catch 
      { 
       // log that property can't be set or throw an exception 
      } 
     } 
     bindingContext.Model = result; 
     return true; 
    } 
} 

和使用

public async Task<HostResponse> GetHostInfo([FromUri(BinderType = typeof(DataMemberBinder))] HostInfo hostInfo) 

在快速搜索我無法找到任何AttributeBased粘結劑嘗試,如果你願意分享找到它

+0

這個工程。謝謝。 – CSharper

0

使用您的Hostinfo中類改變你的調用:

http://{{url}}/Host?hostInfo.host_name=Test&hostInfo.host_zipcode=123&hostInfo.host_id=123

由於查詢字符串長度的限制,如果可能的話,我會建議將路由更改爲接受體內的複雜類型。