繁体   English   中英

如何在Web Api 2中自定义FromUri收到的解析?

[英]How to customise the parsing received with FromUri in Web Api 2?

当webservice尝试从通过[FromUri]参数接收的复杂类型(类)进行解析时,我想自定义绑定某些属性的方式。

控制器方法

[HttpGet]
[Route("Test")]
public IHttpActionResult ComplexPropertiesTest([FromUri] MyComplexPropertiesClass parameters)

班级

 public class MyComplexPropertiesClass
    {
        public DateTime TestTime { get; set; }

        public IEnumerable<int> TestIntEnumeration { get; set; }

        public int SimpleInt { get; set; }

        public string SimpleString { get; set; }

        // More properties...
    }

需要使用yyyyMMddTHHmmss日期格式从字符串中解析TestTime ,并且只需要存储时间部分HHmmss

TestEnumeration可以像5,20,50,100,9这样的字符串接收,并且必须存储为IEnumerable[int]

URL示例:

http://www.example.com/test?TestTime=20170303T091500&TestEnumeration=5,20,50,100,9.

我在http://www.vickram.me/custom-datetime-model-binding-in-asp-net-web-api/中尝试了HttpParameterBinding方法,但只有当我将控制器方法更改为:

public IHttpActionResult ComplexPropertiesTest ([ModelBinder(typeof(CommaSeparatedIntegerCollectionModelBinder))] IEnumerable<int> TestIntEnumeration, …all the other parameters…)`

但这不是一个好的解决方案,因为我需要修改控制器以手动将每个参数分配给新的MyComplexPropertiesClass实例的属性。

另外,我在http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/尝试了CommaDelimitedCollectionModelBinder方法

internal class CustomModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (val?.AttemptedValue == null)
        {
            return false;
        }
   }
}

我收到parameters在bindingContext.ModelName,但在逻辑上没有ValueProviderMyComplexPropertiesClass 我可以尝试获取actionContext.Request.RequestUri.Query的值,但是我需要手动解析每个属性并使用反射将值分配给MyComplexPropertiesClass的新实例。 我很乐意手动解析我想要的那些,其余部分利用默认的Web Api 2绑定过程。

请问你能帮帮我吗?

以下是DateTime的类似情况:

使用API​​Controller补充[FromUri]序列化

缺点是应用于每个DateTime属性。 您无法选择要使用此行为的属性。 它也没有解决TestEnumeration的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM