2015-11-01 52 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; 

    } 

} 
相关问题