gpt4 book ai didi

c# - 使用 HttpClient 通过 AttributeRouting 在 URL 中发送日期

转载 作者:太空狗 更新时间:2023-10-29 22:51:55 26 4
gpt4 key购买 nike

我在获取我的 WebAPI 接受的日期范围查询时遇到了一些问题。据我所知,从我读过的所有内容来看,这应该是可行的,但我仍然收到 400 Bad Request 响应。

我的 API 路由如下所示:

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

我正在使用 AttributeRouting 库并根据 this page我请求的 URL 应该没问题。

我的请求 URL 如下所示:

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

我在 Controller RoutePrefix("plots") 上设置了这个,这是 URL 路由的 plots 位的来源。

如果我去掉 DateTime 对象的时间,一切正常,但我需要过去的时间。

最佳答案

经过大量阅读后,我似乎可以做我想做的事,但需要放宽许多有用的安全措施才能做到这一点。由于有一个简单的解决方法,因此在安全风险增加的情况下放松这些措施是没有意义的。

我在 API 上遇到的错误是:

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

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

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

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

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

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

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

在我的客户端代码中是这样使用的:

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;

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

"yyyy-MM-ddTHH:mm:ss"

由此生成的完整 URI 如下所示:

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

希望这对以后的其他人有帮助。

关于c# - 使用 HttpClient 通过 AttributeRouting 在 URL 中发送日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18067712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com