C#HttpWebRequest的日期标题格式 [英] C# HttpWebRequest Date Header Formatting

查看:241
本文介绍了C#HttpWebRequest的日期标题格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做的HttpWebRequest到S3,和我想要的日期头设置是这样的:

I'm making a HttpWebRequest to S3, and I'm trying to set the Date header to something like this:

星期一,2012 7月16日1点16分18秒-0000

"Mon, 16 Jul 2012 01:16:18 -0000"

下面是我已经试过:

string pattern = "ddd, dd MMM yyyy HH:mm:ss -0000";
request.Date = DateTime.ParseExact("Mon, 16 Jul 2012 01:16:18 -0000", pattern, null);

但是,当我看着请求的头,这是我得到:

But, when I look at the headers of the request, here's what I get:

request.Headers.Get("Date");
// "Mon, 16 Jul 2012 07:16:18 GMT"

我认为这可能对请求403的原因。 AWS的错误文档提到:

I believe this may the reason for a 403 on the request. The AWS error docs mention:

403禁止 - 请求时间和之间的差异   服务器的时间是太大。

403 Forbidden - The difference between the request time and the server's time is too large.

获取此日期的任何建议整理出来将大大AP preciated。谢谢!

Any suggestions for getting this date sorted out would be greatly appreciated. Thanks!

推荐答案

有一些事情要澄清:

  • 您的日期模式不正确。

  • Your date pattern is incorrect.

在HttpWebRequest的 request.Date 头只能在.NET Framework 4中得到修改,并根据该文件,在系统。网络命名空间会一直写使用格林尼治标准​​时间(UTC)格式,这个头作为标准形式。因此,无论你可以做格式化你的约会,只要你想,都不行!

The HttpWebRequest request.Date header can be only get modified in .NET Framework 4 and according to the documentation, the System.Net namespace will always write this header as standard form using GMT (UTC) format. So, whatever you can do to format your date as you want, won't work!

在其他.NET framework版本,你将无法修改HttpWebRequest的 request.Date 头,因为它会使用正确的格林尼治标准​​时间的实际日期( UTC),除非你使用一种黑客设置自己的日期格式(见下文)格式。

In other .NET framework versions you won't be able to modify the HttpWebRequest request.Date header because it will use the actual date in correct GMT (UTC) format unless you use a kind of hack to set your own date and format (see below).

有关问题的解决方案(测试工作):

你的进口:

using System.Net;
using System.Reflection;

获取今天的日期格式为:星期一,2012年7月16日1时16分十八秒-0000

string today = String.Format("{0:ddd,' 'dd' 'MMM' 'yyyy' 'HH':'mm':'ss' 'K}", DateTime.Now);

来了棘手的事情,你可以做这个破解HttpWebRequest的日期标题:

(不要做 request.Date =东西; 了,将其替换为以下)

(Don't do request.Date = something; anymore, replace it with the following)

MethodInfo priMethod = request.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
priMethod.Invoke(request.Headers, new[] { "Date", today });

获取日期从你的要求(只是为了测试):

// "myDate" will output the same date as the first moment: 
// Mon, 16 Jul 2012 01:16:18 -0000
// As you can see, you will never get this again:
// Mon, 16 Jul 2012 07:16:18 GMT
string myDate = request.Headers.Get("Date");


在这一点上,你已经成功地建立自己的格式和日期值到HttpWebRequest的日期标题!

希望这有助于: - )

Hope this helps :-)

这篇关于C#HttpWebRequest的日期标题格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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