ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-01 21:52:55  阅读:206  来源: 互联网

标签:c http asp-net asp-net-web-api datetime-format


我们有多个API控制器接受GET请求,如下所示:

//FooController
public IHttpActionResult Get([FromUri]Foo f);
//BarController
public IHttpActionResult Get([FromUri]Bar b);

现在 – 我们希望(或者,被迫)全局更改GET查询字符串中的DateTime字符串格式

"yyyy-MM-ddTHH:mm:ss" -> "yyyy-MM-ddTHH.mm.ss"

更改后,包含DateTime类型的类的所有[FromUri]序列化都将失败.

有没有办法补充[FromUri]序列化以接受查询字符串中的DateTime格式?或者我们是否必须为所有API参数构建自定义序列化以支持新的DateTime字符串格式?

编辑:请求的示例

public class Foo {
 public DateTime time {get; set;}
}

//FooController. Let's say route is api/foo
public IHttpActionResult Get([FromUri]Foo f);

GET api/foo?time=2017-01-01T12.00.00

解决方法:

要在所有模型上应用所有DateTime类型的行为,那么您将要编写一个custom binder for the DateTime type and apply it globally.

DateTime Model Binder

public class MyDateTimeModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(DateTime))
            return false;

        var time = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (time == null)
            bindingContext.Model = default(DateTime);
        else
            bindingContext.Model = DateTime.Parse(time.AttemptedValue.Replace(".", ":"));

        return true;
    }
}

WebAPI配置

config.BindParameter(typeof(DateTime), new MyDateTimeModelBinder());

标签:c,http,asp-net,asp-net-web-api,datetime-format
来源: https://codeday.me/bug/20190701/1351205.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有