【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的园友们速速动起来,跟着博主一起来学习吧.作为程序猿,我们都知道参数和返回值是编程领域不可分割的两大块,此前分享了 ...
随机推荐
- Nginx+tomcat负载均衡时静态页面报404
百度到的问题解决BLOG http://os.51cto.com/art/201204/326843.htm nginx+2台tomcat负载均衡,应用程序已部署,单独访问tomcat时,可以访问到所 ...
- 2-4. Using auto with Functions
在C++14中允许使用type deduction用于函数参数和函数返回值 Return Type Deduction in C++11 #include <iostream> using ...
- 关于读取txt文件中文乱码问题
在处理文件的过程中,读取txt文件出现中文乱码.这种情况是由于编码字符不一致导致. public static string ReadFile(string path, string fileName ...
- base64/62 加解密的实现。
base64/62加解密代码下载地址: http://files.cnblogs.com/files/Kingfans/base64(62)加解密.zip base64: base62:
- [翻译][erlang]cowboy handler模块的使用
关于Cowboy Cowboy是基于Erlang实现的一个轻量级.快速.模块化的http web服务器. Handlers,用于处理HTTP请求的程序处理模块. Plain HTTP Handlers ...
- 引用64位dll时候出现 未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项。试图加载格式不正确的程序。
引用64位dll时候出现 未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项.试图加载格式不正确的程序. 需要在web.config增加配置 <startup use ...
- ActionScript 3.0 自写类整理笔记(十三)——Random类
一个简单的随机函数工具类,总共提供了9种静态方法来获取不同的随机值随便写的,如果你还有什么更好的建议,请提出来,谢谢~ index.Random类:代码:public final class Rand ...
- SQLServer数据库中创建临时表
IF object_id('tempdb..#jimmy') is not NULL BEGIN DROP TABLE #jimmy; END IF object_id('tempdb..#jimmy ...
- CM+CDH安装遇到的问题
1.实在是在安装CDH的时候无法安装成功的话,只有重新启动了,下面给大家分享一个神器,按照这个脚本应该差不多就能卸载干净,然后重新安装,写一个脚本,内容如下,救命的神器呀: #!/bin/bash s ...
- bzoj1179(Atm)
---恢复内容开始--- 1179: [Apio2009]Atm Time Limit: 15 Sec Memory Limit: 162 MB Description Input 第一行包含两个整 ...