简体   繁体   English

正确转义URI以便在HttpClient.PostAsync中使用需要什么?

[英]What's required to properly escape a URI for use in HttpClient.PostAsync?

Most overloads of HttpClient.PostAsync() allow either a string or URI to be passed in. Some however (in the Formatting namespace) only allow a string. HttpClient.PostAsync()大多数重载都允许传递字符串或URI 。但是,某些(在Formatting名称空间中)仅允许传递字符串。 To use this, I build and use a URI string like: 要使用此功能,我将构建并使用一个URI字符串,例如:

string uri = "http://myserver.com/" + userSuppliedName + "/dosomething/";
client.PostAsync(uri, someObject, formatter);

My concern now is that userSuppliedName can be something invalid or malicious, so I want to make sure it is escaped properly. 现在,我担心的是userSuppliedName可能是无效或恶意的,因此我想确保它已正确转义。 In the documentation for System.Uri , it states that by default a passed in string will be escaped properly, but since the PostAsync method I'm using only supports a string URI, I want to check: will it escape properly automatically? System.Uri的文档中,它声明默认情况下传入的字符串将被正确转义,但是由于我使用的PostAsync方法仅支持字符串URI,因此我想检查一下:它会自动正确转义吗? If not, should I just be escaping userSuppliedName when constructing string uri instead? 如果不是,在构造string uri时是否应该转义userSuppliedName

You can pass new Uri(uri).AbsoluteUri as the first parameter and alleviate encoding issues. 您可以将new Uri(uri).AbsoluteUri作为第一个参数,以减轻编码问题。 It'll do it for you. 会帮你的。

Use Uri.EscapeDataString() 使用Uri.EscapeDataString()

string uri = "http://myserver.com/" + Uri.EscapeDataString(userSuppliedName) + "/dosomething/";
client.PostAsync(uri, someObject, formatter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM