Я потратил целый день, пытаясь разрешить это. У меня есть пользовательский веб-сервер, и его запросы от клиента Chrome или POSTman ReST работают нормально. Как только я использую webclient или httpwebrequest в С#, я получаю: сервер совершил нарушение протокола. Раздел = ResponseStatusLine при попытке передать zip файл клиенту.
Я пытался:
public static bool SetAllowUnsafeHeaderParsing20()
{
//Get the assembly that contains the internal class
Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
if (aNetAssembly != null)
{
//Use the assembly in order to get the internal type for the internal class
Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
if (aSettingsType != null)
{
//Use the internal static property to get an instance of the internal settings class.
//If the static instance isn't created allready the property will create it for us.
object anInstance = aSettingsType.InvokeMember("Section", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
if (anInstance != null)
{
//Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
if (aUseUnsafeHeaderParsing != null)
{
aUseUnsafeHeaderParsing.SetValue(anInstance, true);
return true;
}
}
}
}
return false;
}
а также
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
в app.config.
Я также попытался keep-alive = false и перепутал с заголовками тоже /
Это веб-запрос, который терпит неудачу при вызове client2Downloadfile:
private void sendManifest()
{
Uri remoteuri = new Uri(Properties.Settings.Default.masterurl);
SetAllowUnsafeHeaderParsing20();
using (WebClient client = new WebClient())
{
NameValueCollection reqparm = new NameValueCollection();
reqparm.Add("application", "TestApp");
reqparm.Add("manifest", manifest);
try
{
byte[] responsebytes = client.UploadValues(Properties.Settings.Default.masterurl, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
if (responsebody != "")
{
using (WebClient client2 = new WebClient())
{
client2.DownloadFile(Properties.Settings.Default.masterurl + "//" + responsebody + "transfer.zip", "c:\\temp.zip");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Ответ веб-сервера можно увидеть по адресу:
http://gplus2.net:9532/97e456f0-9b57-4315-b03d-40a67f76d440/transfer.zip
Любая помощь очень ценится, поскольку у меня буквально заканчиваются идеи. Очевидно, это неправильный заголовок сервера, но я сохранил его до минимума.
У меня была та же проблема, и я решил ее, используя следующий метод. Я создал пользовательский веб-клиент, который переопределяет GetWebRequestMethod.
class CustomWebClient : WebClient
{
/// <summary>
/// Returns a <see cref="T:System.Net.WebRequest" /> object for the specified resource.
/// </summary>
/// <param name="address">A <see cref="T:System.Uri" /> that identifies the resource to request.</param>
/// <returns>
/// A new <see cref="T:System.Net.WebRequest" /> object for the specified resource.
/// </returns>
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).KeepAlive = false;
}
return request;
}
}
Затем я сделал запрос обычным способом, как это
using (CustomWebClient client = new CustomWebClient())
{
client.Headers[HttpRequestHeader.Authorization] = "Basic " + base64String;
responseData = client.DownloadData(baseUri);
}
Я долгое время боролся с этой проблемой, и в конечном итоге проблема заключалась в настраиваемом заголовке, который я добавил в IIS... Я скопировал значение где-то и содержал {cr}:
Откройте диспетчер IIS → перейдите на веб-сайт → в виде содержимого, выберите "Заголовки ответов".
проверьте пользовательские заголовки в IIS, удалите заголовки, если они не нужны, а также посмотрите, имеет ли заголовок неверное значение.
httpClient.PostAsync
?