C# 如何在单个请求的 HttpWebRequest 中禁用“Expect: 100 continue”标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14063327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:34:57  来源:igfitidea点击:

How to disable the "Expect: 100 continue" header in HttpWebRequest for a single request?

c#.nethttpwebrequest

提问by Roman Starkov

HttpWebRequestautomatically appends an Expect: 100-continueheader for POST requests. Various sources around the internet suggest that this can be disabled as follows:

HttpWebRequest自动Expect: 100-continue为 POST 请求附加一个标头。互联网上的各种来源表明,可以按如下方式禁用此功能:

System.Net.ServicePointManager.Expect100Continue = false;

However, I'm writing a library and I cannot disable this for the entire appdomain, in case the application relies on this behaviour. Nor can I assume that it will remain set to this value. How can I disable it for a specific request?

但是,我正在编写一个库,我无法为整个应用程序域禁用它,以防应用程序依赖此行为。我也不能假设它会保持设置为这个值。如何针对特定请求禁用它?

采纳答案by Roman Starkov

The HttpWebRequestclass has a property called ServicePointwhich can be used to change this setting for a specific request. For example:

HttpWebRequest类有一个称为属性ServicePoint,其可以用来改变此设置的特定请求。例如:

var req = (HttpWebRequest) WebRequest.Create(...);
req.ServicePoint.Expect100Continue = false;

回答by AroglDarthu

If you also need to set a proxy, make sure to do that first. Otherwise Expect100Continuewill be reverted to trueagain. So:

如果您还需要设置代理,请务必先执行此操作。否则Expect100Continue将再次恢复为true。所以:

HttpWebRequest webRequest = WebRequest.CreateHttp(_url);
webRequest.Proxy = new WebProxy(_proxyHost, _proxyPort);
webRequest.ServicePoint.Expect100Continue = false;