传递DateTimeOffset作为WebAPI查询字符串 [英] Passing DateTimeOffset as WebAPI query string

查看:61
本文介绍了传递DateTimeOffset作为WebAPI查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的WebAPI操作:

I've got a WebAPI action that looks like so:

[Route("api/values/{id}")]
public async Task<HttpResponseMessage> Delete(string id, DateTimeOffset date) {
    //do stuff
}

但是当我从 HttpClient 实例调用它时,创建如下网址:

But when I invoke this from a HttpClient instance, making a URL like:

string.Format("http://localhost:1234/api/values/1?date={0}", System.Net.WebUtility.UrlEncode(DateTimeOffset.Now.ToString()));
// -> "http://localhost:1234/api/values/1?date=17%2F02%2F2015+7%3A18%3A39+AM+%2B11%3A00"

我得到一个 400 的响应,说非空参数 date 不存在。

I get a 400 response back saying that the non-nullable parameter date does not exist.

我也尝试将 [FromUri] 属性添加到参数中但它仍然无法映射。如果将其更改为 DateTimeOffset?,我可以看到它保留为空,并查看 Request.RequestUri.Query

I've also tried adding the [FromUri] attribute to the parameter but it still doesn't map through. If I change it to be DateTimeOffset? I can see it is left as null and looking at Request.RequestUri.Query the value is there, just not mapped.

最后,我尝试不使用 WebUtility.UrlEncode ,但没有

Finally I tried not doing a WebUtility.UrlEncode and it made no different.

推荐答案

该问题已由400响应消息准确描述,尽管可能更清楚了。根据属性定义,该路线仅需要一个参数 id ,但是Delete方法需要一个名为 date 的参数。

The problem is being described exactly by the 400 response message, although it could have been more clear. The route, as defined by the attribute, only expects a parameter id, but the Delete method expects another parameter called date.

如果要使用查询字符串提供此值,则需要使用 DateTimeOffset?使该参数为可空值,这还将其转换为可选参数。如果日期是必填字段,请考虑将其添加到路线中,例如:

If you want to provide this value using the query string, you'll need to make that parameter nullable, by using "DateTimeOffset?", which would also transform it into an optional parameter. If the date is a required field, consider adding it to the route, like:

[Route("api/values/{id}/{date}")]

好,忽略我在上面键入的内容,这只是一个格式问题。 Web API无法弄清楚解析给定值所需的区域性,但是如果您尝试在查询字符串中使用JSON格式(例如2014-05-06T22:24:55Z)传递DateTimeOffset,那应该可以。

OK, ignore what I typed above, it's just a formatting problem. Web API has trouble figuring out the culture needed to parse the given value, but if you try to pass on DateTimeOffset using a JSON format in the query string, like 2014-05-06T22:24:55Z, that should work.

这篇关于传递DateTimeOffset作为WebAPI查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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