使用HttpClient使用AttributeRouting在URL中发送日期

Jam*_*mer 5 c# datetime asp.net-web-api attributerouting

我在获取WebAPI接受的日期范围查询时遇到了一些问题.据我所知,我所读到的一切应该可行,但我仍然得到400 Bad Request回应.

我的API路线如下所示:

    [System.Web.Http.HttpGet]
    [GET("range/{start:datetime}/{end:datetime}")]
    public HttpResponseMessage Get(DateTime start, DateTime end)
Run Code Online (Sandbox Code Playgroud)

我正在使用该AttributeRouting库,根据此页面,我要求的URL应该没问题.

我的请求网址如下所示:

http://localhost:51258/plots/range/2013-07-29T21:58:39/2013-08-05T21:58:39
Run Code Online (Sandbox Code Playgroud)

我在控制器上有这个设置,RoutePrefix("plots")这是plotsURL路由的位来自.

如果我把时间从DateTime物体上移开,一切正常,但我需要时间过去.

Jam*_*mer 7

经过大量的阅读后,似乎可以做我试图做的事情,但它需要放松许多有用的安全措施才能这样做.由于存在简单的解决方法,因此考虑到增加的安全风险而放松这些措施是没有意义的.

我在API上遇到的错误是:

A potentially dangerous Request.Path value was detected from the client (:)
Run Code Online (Sandbox Code Playgroud)

显然,这是用于分隔DateTime字符串时间部分元素的冒号字符.所以我做了以下更改.

我的Api动作方法现在看起来像这样:

[System.Web.Http.HttpGet]
[GET("range?{startDate:datetime}&{endDate:datetime}")]
public HttpResponseMessage Get(DateTime startDate, DateTime endDate)
Run Code Online (Sandbox Code Playgroud)

现在,日期定义为查询字符串的一部分,而不是路径本身的一部分.

要处理查询字符串的创建,我还有以下扩展方法:

public static string ToQueryString(this NameValueCollection source, bool removeEmptyEntries)
{
    return source != null ? "?" + String.Join("&", source.AllKeys
        .Where(key => !removeEmptyEntries || source.GetValues(key).Any(value => !String.IsNullOrEmpty(value)))
        .SelectMany(key => source.GetValues(key)
            .Where(value => !removeEmptyEntries || !String.IsNullOrEmpty(value))
            .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
        .ToArray())
        : string.Empty;
}
Run Code Online (Sandbox Code Playgroud)

这在我的客户端代码中使用如下:

var queryStringParams = new NameValueCollection
    {
        {"startDate", start.ToString(_dateService.DefaultDateFormatStringWithTime)},
        {"endDate", end.ToString(_dateService.DefaultDateFormatStringWithTime)}
    };

var response = httpClient.GetAsync(ApiRootUrl + "plots/range" + queryStringParams.ToQueryString(true)).Result;
Run Code Online (Sandbox Code Playgroud)

我的应用程序中的日期服务只提供默认的日期格式字符串并使用此模式:

"yyyy-MM-ddTHH:mm:ss"
Run Code Online (Sandbox Code Playgroud)

从中生成的完整URI如下所示:

http://localhost:51258/plots/range?startDate=2013-07-30T21%3A48%3A26&endDate=2013-08-06T21%3A48%3A26
Run Code Online (Sandbox Code Playgroud)

希望这有助于将来的其他人.