C# WebRequest.getResponse(): 400 Bad Request

前端 未结 2 620
甜味超标
甜味超标 2020-12-06 12:34

I am trying to download a file from a server using System.Web. It actually works, but some links give me trouble. The links look like this:

http://cdn.somesi         


        
相关标签:
2条回答
  • 2020-12-06 13:02

    By default, the Uri class will not allow an escaped / character (%2f) in a URI (even though this appears to be legal in my reading of RFC 3986).

    Uri uri = new Uri("http://example.com/embed%2fded");
    Console.WriteLine(uri.AbsoluteUri); // prints: http://example.com/embed/ded
    

    (Note: don't use Uri.ToString to print URIs.)

    According to the bug report for this issue on Microsoft Connect, this behaviour is by design, but you can work around it by adding the following to your app.config or web.config file:

    <uri>
      <schemeSettings>
        <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
      </schemeSettings>
    </uri>
    

    (Since WebRequest.Create(string) just delegates to WebRequest.Create(Uri), you would need to use this workaround no matter which method you call.)

    0 讨论(0)
  • 2020-12-06 13:05

    This has now changed in .NET 4.5. By default you can now use escaped slashes. I posted more info on this (including screenshots) in the comments here: GETting a URL with an url-encoded slash

    0 讨论(0)
提交回复
热议问题