【AspNetCore】【WebApi】扩展Webapi中的RouteConstraint中,让DateTime类型,支持时间格式化(DateTimeFormat)
扩展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。
一个无参数的,用来兼容默认无参的情况。
别的不多说了,直接上代码。
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.cs 的 ConfigureServices 方法,添加
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)的更多相关文章
- mysql中的sql-mode导致的datetime类型字段不能为0000
问题描述: 在执行建表语句的时候,出现invalid default datetime value '0000-00-00 00:00:00',从字面意思看,就是不合法的默认值'0000-00-00 ...
- SQL中DATE和DATETIME类型不能直接作比较
如题,今天纠结了一天的问题. 在存储过程中定义了两个datetime类型的时间,然后把这个两个时间作为where条件中一个date字段between的两个时间段,结果无论如何都不执行... 就像 u ...
- Mysql一个非常有用的内置函数今天碰到要把MySQL数据库中的varchar转换成date类型进
Mysql一个非常有用的内置函数 今天碰到要把MySQL数据库中的varchar转换成date类型进行时间的比较和查询.在网上找了找,发现MySQL也跟其他数据库一样有自己内置的转换函数:str_to ...
- C# WebAPI中DateTime类型字段在使用微软自带的方法转json格式后默认含T的解决办法
原文:C# WebAPI中DateTime类型字段在使用微软自带的方法转json格式后默认含T的解决办法 本人新手,在.Net中写WebAPI的时候,当接口返回的json数据含有日期时间类型的字段时, ...
- 使用Swashbuckle.AspNetCore生成.NetCore WEBAPI的接口文档
一.问题 使用Swashbuckle.AspNetCore生成.NetCore WEBAPI的接口文档的方法 二.解决方案 参考文章:https://docs.microsoft.com/zh-cn/ ...
- Day_11【集合】扩展案例2_使用普通for循环获取集合中索引为3的元素并打印,统计集合中包含字符串"def"的数量,删除集合中的所有字符串",将集合中每个元素中的小写字母变成大写字母def",
分析以下需求,并用代码实现 1.定义ArrayList集合,存入多个字符串"abc" "def" "efg" "def" ...
- C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 C#进阶系列——WebApi接口传参不再困惑:传参详解 ...
- vs中开发web站点使IIS Express支持局域网连接
vs中开发web站点使IIS Express支持局域网连接 在开发webapi的时候,客户端设备都会使用局域网的地址访问webapi,有时候需要调试api.这个时候就需要使用一些技巧了,这里我记录了我 ...
- WebApi接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.作为程序猿,我们都知道参数和返回值是编程领域不可分割的两大块,此前分享了 ...
随机推荐
- Only the sqlmigrate and sqlflush commands can be used when an app has migrations.
samcao@samcao-Lenovo-IdeaPad-Y470:~/caodjango/caossh$ python manage.py sqlall getssh System check id ...
- PHP 图片生成文字
$dst_path = './1.png'; $font_file = './ADOBEHEITISTD-REGULAR (V5.010).OTF'; $img_bg = imagecreatefro ...
- php嵌套数组递归搜索返回数组key
var rewardTypes={"experience":{"\u7ecf\u9a8c\u503c":{"1":"\u660e\ ...
- Maven中配置默认JDK版本
使用Maven构建项目时,默认是使用jdk1.3版本,目前很多使用泛型的项目肯定是无法通过编译,除了修改项目的pom文件外,还可以在Maven的配置文件settings.xml中添加如下配置来解决: ...
- SQLite in Windows Store Apps
Using SQLite in Windows Store Apps : https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Using-SQL ...
- SQL Server Update 语句使用Nolock 语法
Update talblename set Column='XX' from Table TableName with(nolock) where XXX
- 【温故Delphi】Win32API之GetTempFileName
所遇问题 新建的算量工程文件暂时保存到临时文件中,代码中调用了Win32 API——GetTempFileName 但在一台笔记本上,函数返回了一个空字符串! 为了查明原因想到了好用的GetLastE ...
- json数据测试接口
json数据测试接口:http://www.xiaoqiang.org/tools/JsonView/?1348068433
- Qt ffmpeg环境搭建
ffmpeg下载地址:https://ffmpeg.zeranoe.com/builds/ 版本选择第一个,然后多少位看自己的pc(我的是64),右边对应三个都要下载,Static,Shared,De ...
- loadrunner回放脚本报错27780:“[10053] 软件导致连接中止”
录制的脚本在回放时报错,错误如下: vuser_init.c(12): 警告 -26627: 对于“http://bsp.paycenter.58.com.cn/favicon.ico”,HTTP 状 ...