扩展Webapi中的RouteConstraint中,让DateTime类型,支持时间格式化(DateTimeFormat)

一、背景

大家在使用WebApi时,会用到DateTime为参数,类似于这样:

//url: xxx/2016-09-08
[HttpGet("{date:datetime}")]
public string Get(DateTime date)
{
return date.ToString("yyyyMMdd");
}

但是":datetime" 支持这样的格式:

12/25/2009
11:45:00 PM
11:45:00
11:45
Apr 5 2009 11:45:00 PM
April 5 2009 11:45:00 PM
12/25/2009 11:45:00 PM
11:45:00 PM
2009-05-12T11:45:00Z

但我们有的时候想要的是类似这样的格式:

20091225
091225
12252009

或是各种自定义的时间格式。

二、目的

用简单的办法来自定义这个时间格式。比如正则":regex"是支持参数的,我们让默认的":datetime"来支持一个参数。 比如":datetime(yyyyMMdd)"

三、实现

要做一个自定义的 RouteConstraint ,我们要实现一个接口 IRouteConstraint



但我们可以偷个懒,我们找到DateTimeRouteConstraint的源码,做一些修改。

Routing 源码地址 :https://github.com/aspnet/Routing

找到 Routing/src/Microsoft.AspNetCore.Routing/Constraints/DateTimeRouteConstraint.cs

源码:

public class DateTimeRouteConstraint : IRouteConstraint
{
/// <inheritdoc />
public bool Match(
HttpContext httpContext,
IRouter route,
string routeKey,
RouteValueDictionary values,
RouteDirection routeDirection)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (route == null)
{
throw new ArgumentNullException(nameof(route));
}
if (routeKey == null)
{
throw new ArgumentNullException(nameof(routeKey));
}
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
object value;
if (values.TryGetValue(routeKey, out value) && value != null)
{
if (value is DateTime)
{
return true;
}
DateTime result;
var valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
return DateTime.TryParse(valueString, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
}
return false;
}
}

我们来对这个做一点修改。给他增加两个构造函数。

一个有一个string参数,用来接受DateTimeFormat。
一个无参数的,用来兼容默认无参的情况。

别的不多说了,直接上代码。

DateTimeExRouteConstraint.cs

public class DateTimeExRouteConstraint : IRouteConstraint
{
private readonly string _dateTimeformat;
public DateTimeExRouteConstraint(string p_dateTimeformat)
{
_dateTimeformat = p_dateTimeformat;
}
public DateTimeExRouteConstraint()
{
}
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (route == null)
{
throw new ArgumentNullException(nameof(route));
}
if (routeKey == null)
{
throw new ArgumentNullException(nameof(routeKey));
}
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
object value;
if (values.TryGetValue(routeKey, out value) && value != null)
{
if (value is DateTime)
{
return true;
}
DateTime result;
var valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(_dateTimeformat))
{
var success = DateTime.TryParseExact(valueString, _dateTimeformat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (success)
{
values[routeKey] = result;
}
return success;
}
return DateTime.TryParse(valueString, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
}
return false;
}
}

然后我们用这个新的 DateTimeExRouteConstraint 来替换默认的 RouteConstraint

找到 Startup.csConfigureServices 方法,添加

services.Configure<RouteOptions>(options => options.ConstraintMap["datetime"] = typeof(DateTimeExRouteConstraint));

四、使用

实现以后,我们就可以愉快的使用的DateTimeFormat 的方式了。



比如这样

//url: xxx/20160908
[HttpGet("{date:datetime(yyyyMMdd)}")]
public string Get(DateTime date)
{
return date.ToString();
}

或者这样

//url: xxx/160908
[HttpGet("{date:datetime(yyMMdd)}")]
public string Get(DateTime date)
{
return date.ToString();
}

再或者这样

//url: xxx/09082016
[HttpGet("{date:datetime(MMddyyyy)}")]
public string Get(DateTime date)
{
return date.ToString();
}

全看你喜欢了。

本文地址:

http://www.cnblogs.com/gaoshang212/p/5855931.html

【AspNetCore】【WebApi】扩展Webapi中的RouteConstraint中,让DateTime类型,支持时间格式化(DateTimeFormat)的更多相关文章

  1. mysql中的sql-mode导致的datetime类型字段不能为0000

    问题描述: 在执行建表语句的时候,出现invalid default datetime value '0000-00-00 00:00:00',从字面意思看,就是不合法的默认值'0000-00-00 ...

  2. SQL中DATE和DATETIME类型不能直接作比较

    如题,今天纠结了一天的问题. 在存储过程中定义了两个datetime类型的时间,然后把这个两个时间作为where条件中一个date字段between的两个时间段,结果无论如何都不执行... 就像  u ...

  3. Mysql一个非常有用的内置函数今天碰到要把MySQL数据库中的varchar转换成date类型进

    Mysql一个非常有用的内置函数 今天碰到要把MySQL数据库中的varchar转换成date类型进行时间的比较和查询.在网上找了找,发现MySQL也跟其他数据库一样有自己内置的转换函数:str_to ...

  4. C# WebAPI中DateTime类型字段在使用微软自带的方法转json格式后默认含T的解决办法

    原文:C# WebAPI中DateTime类型字段在使用微软自带的方法转json格式后默认含T的解决办法 本人新手,在.Net中写WebAPI的时候,当接口返回的json数据含有日期时间类型的字段时, ...

  5. 使用Swashbuckle.AspNetCore生成.NetCore WEBAPI的接口文档

    一.问题 使用Swashbuckle.AspNetCore生成.NetCore WEBAPI的接口文档的方法 二.解决方案 参考文章:https://docs.microsoft.com/zh-cn/ ...

  6. Day_11【集合】扩展案例2_使用普通for循环获取集合中索引为3的元素并打印,统计集合中包含字符串"def"的数量,删除集合中的所有字符串",将集合中每个元素中的小写字母变成大写字母def",

    分析以下需求,并用代码实现 1.定义ArrayList集合,存入多个字符串"abc" "def" "efg" "def" ...

  7. C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解

    前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 C#进阶系列——WebApi接口传参不再困惑:传参详解  ...

  8. vs中开发web站点使IIS Express支持局域网连接

    vs中开发web站点使IIS Express支持局域网连接 在开发webapi的时候,客户端设备都会使用局域网的地址访问webapi,有时候需要调试api.这个时候就需要使用一些技巧了,这里我记录了我 ...

  9. WebApi接口返回值不困惑:返回值类型详解

    前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.作为程序猿,我们都知道参数和返回值是编程领域不可分割的两大块,此前分享了 ...

随机推荐

  1. .net 控件

    DevComponents.DotNetBar11.8.0.0:百度网盘里 DevExpress13.2.8:百度网盘里

  2. oracle 存储过程 包 【转】

    一.为什么要用存储过程? 如果在应用程序中经常需要执行特定的操作,可以基于这些操作简历一个特定的过程.通过使用过程可以简化客户端程序的开发和维护,而且还能提高客户端程序的运行性能. 二.过程的优点? ...

  3. python第一天基础1-1

    win下是没有多进程的 windows:1.下载安装包 https://www.python.org/downloads/2.安装 默认安装路径:C:\python273.配置环境变量 [右键计算机] ...

  4. python核心编程笔记

    1.python的对象是通过引用传递的. 2.多元赋值: x, y = y, x

  5. 在DW 5.5+PhoneGap+Jquery Mobile下搭建移动开发环境

    移动设备应用开发有多难,只要学会HTML5+Javascript就可以.用Dreamweaver5.5+PhoneGap+Jquery Mobile搭建移动开发环境,轻轻松松开发你自己的应用.让你用普 ...

  6. session和cookie的简单理解

    0. 引子,我们为什么要cookie和session       因为http请求是无状态的(不能记录用户的登录状态等),所以需要某种机制来保存用户的登录状态等信息,在下次访问web服务的时候,不用再 ...

  7. Async and Await

    http://blog.stephencleary.com/2012/02/async-and-await.html Most people have already heard about the ...

  8. MATLAB 画出三个通信小区cell边界示意图

    d=1000; %两个小区中心间距离的一半 rcell=2*d/sqrt(3); %小区半径 ncell=3; %小区个数 cellposition=zeros(ncell,2); %初始化小区中心位 ...

  9. bower

    1. bower介绍 Bower 是 twitter 推出的一款包管理工具,基于nodejs的模块化思想,把功能分散到各个模块中,让模块和模块之间存在联系,通过 Bower 来管理模块间的这种联系. ...

  10. asp.net core 使用protobuf

    在一些性能要求很高的应用中,使用protocol buffer序列化,优于Json.而且protocol buffer向后兼容的能力比较好. 由于Asp.net core 采用了全新的MiddleWa ...