使用HttpClient的发送日期URL中使用AttributeRouting [英] Using HttpClient to Send Dates in URL Using AttributeRouting

查看:216
本文介绍了使用HttpClient的发送日期URL中使用AttributeRouting的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题让我的的WebAPI接受的日期范围查询。由于据我可以告诉的一切我读过这应该是工作,但我仍然获得 400错误的请求响应。

我的API的路线是这样的:

  [System.Web.Http.HttpGet]
    [GET(范围/ {开始:日期时间} / {结束:日期时间})]
    公众的Htt presponseMessage获取(DateTime的开始,结束日期时间)

我使用了 AttributeRouting 库,并根据<一个href=\"http://www.asp.net/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing\"相对=nofollow>此页面我请求URL应该罚款。

我的请求的URL看起来是这样的:

 的http://本地主机:51258 /图/范围/ 2013-07-29T21:58:39 / 2013-08-05T21:58:39

我有这一套控制器路线preFIX(自留地)这是在哪里的的URL路径位来自

如果我脱光了时代离的DateTime 反对一切工作正常,但我需要传递的时间。


解决方案

做的大量阅读后看来,它是可以做到什么,我试图做的,但它需要为了放松了很多有用的保安措施,这样做。既然有一个简单的解决方法,它只是没有意义在增加安全隐患光放宽这些措施。

我是在API得到的错误是:

 从客户端检测到有潜在危险的Request的值(:)

显然,这是用来的DateTime 字符串的时间部分的元素分离结肠字符。所以我做了以下修改。

我的API操作方法现在看起来是这样的:

  [System.Web.Http.HttpGet]
[GET(?{范围开始日期:日期时间}&放大器; {结束日期:日期时间})]
公众的Htt presponseMessage获取(日期时间的startDate,日期结束日期)

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

要处理的查询字符串我也有下面的扩展方法创建:

 公共静态字符串ToQueryString(这NameValueCollection中源,布尔removeEmptyEntries)
{
    返回源!= NULL? ? +的string.join(与&amp;,source.AllKeys
        。凡(键=&GT;!removeEmptyEntries || source.GetValues​​(密钥)。任何(值=&GT;!String.IsNullOrEmpty(值)))
        .SelectMany(键=&GT; source.GetValues​​(钥匙)
            。凡(价值=&GT;!removeEmptyEntries || String.IsNullOrEmpty(值))
            。选择(价值=&GT;的String.Format({0} = {1},HttpUtility.UrlEn code(键),值= NULL HttpUtility.UrlEn code(值):串!?。空)))
        .ToArray())
        :的String.Empty;
}

这是我的客户code使用的是这样的:

  VAR queryStringParams =新的NameValueCollection
    {
        {的startDate,start.ToString(_dateService.DefaultDateFormatStringWithTime)},
        {结束日期,end.ToString(_dateService.DefaultDateFormatStringWithTime)}
    };VAR响应= httpClient.GetAsync(ApiRootUrl +图/范围+ queryStringParams.ToQueryString(真))结果。

在我的申请之日起的服务只是提供默认的日期格式字符串,并使用此模式:

 YYYY-MM-DDTHH:MM:SS

这是从这个生产的完整URI是这样的:

<$p$p><$c$c>http://localhost:51258/plots/range?startDate=2013-07-30T21%3A48%3A26&endDate=2013-08-06T21%3A48%3A26

希望这可以帮助别人,将来别人。

I'm having some problems getting a date range query accepted by my WebAPI. As as far as I can tell from everything I've read this should be working but I still get 400 Bad Request responses.

My API route looks like this:

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

I'm using the AttributeRouting library and according to this page the URL I'm requesting should be fine.

My request URL looks like this:

http://localhost:51258/plots/range/2013-07-29T21:58:39/2013-08-05T21:58:39

I have this set on the controller RoutePrefix("plots") which is where the plots bit of the URL route comes from.

If I strip the times off the DateTime objects everything works fine but I need the times passed.

解决方案

After doing a lot of reading it appears that it is possible to do what I was attempting to do but it requires relaxing a lot of useful security measures in order to do so. Since there is a simple workaround it just doesn't make sense to relax these measures in light of increased security risks.

The error I was getting at the API was:

A potentially dangerous Request.Path value was detected from the client (:)

Obviously this is the colon characters used to separate the elements of the time portion of the DateTime string. So I have made the following changes.

My Api action method now looks like this:

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

The dates are now defined as part of the query string rather than parts of the path itself.

To handle the creation of the query string I also have the following extension method:

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;
}

Which is used in my client code like this:

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;

The date service in my application simply provides the default date formatting string and uses this pattern:

"yyyy-MM-ddTHH:mm:ss"

The complete URI that is produced from this looks like:

http://localhost:51258/plots/range?startDate=2013-07-30T21%3A48%3A26&endDate=2013-08-06T21%3A48%3A26

Hope this helps someone else in the future.

这篇关于使用HttpClient的发送日期URL中使用AttributeRouting的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆