How to encode/decode url strings in an UWP App

时光怂恿深爱的人放手 提交于 2019-12-23 09:11:41

问题


I'm building a UWP App which communicates with a Web-Api. At some Point I'm sending a string in the url to the Web-Api which can be manipulated by the user. Because of that the string can include characters which could do evil things to the Web-Api.
For example:
This is my UserController

[Route("api/user/{uid}")]
public User GetUser(string uid)
{
   return userRepository.GetByUid(uid);
}

For the sake of this example we assume that the user can put in the uid manually in a textbox. Now if he puts in

../vipuser

He could have access to the VipUserController. Because the ../ goes one hirachy up.

I searched a little and found this SO article which recommends the use of System.Web.UrlEncodeUnicode and System.Web.UrlDecode.

But since UWP Apps doesn't include the System.Web namespace I was wondering if there is an alternative to this methods, which I can use into a UWP-App?


回答1:


Uri.EscapeDataString() and Uri.UnescapeDataString() will do the trick.




回答2:


Prefer System.Net.WebUtility.UrlDecode and System.Net.WebUtility.UrlEncode over the methods on Uri.

This is because WebUtility handles space ( ) and plus (+) consistently across both "multipart/form-data" and "application/x-www-form-urlencoded" encodings.



来源:https://stackoverflow.com/questions/34316154/how-to-encode-decode-url-strings-in-an-uwp-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!