System.Net.WebUtility.UrlEncode(string)

Here are the examples of the csharp api System.Net.WebUtility.UrlEncode(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

538 Examples 7

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : onybo

public virtual async Task<(HttpStatusCode, QueryResult<T[]>)> Query<T>(string query, bool excludeDrafts = true)
        {
            var encodedQ = System.Net.WebUtility.UrlEncode(query);
            var message = await _httpClient.GetAsync($"query/{_dataset}?query={encodedQ}").ConfigureAwait(false);
            return await QueryResultToResult<QueryResult<T[]>, T>(message, excludeDrafts).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : onybo

public virtual async Task<(HttpStatusCode, QueryResult<T>)> QuerySingle<T>(string query)
        {
            var encodedQ = System.Net.WebUtility.UrlEncode(query);
            var message = await _httpClient.GetAsync($"query/{_dataset}?query={encodedQ}").ConfigureAwait(false);
            return await QueryResultToResult<QueryResult<T>, T>(message).ConfigureAwait(false);
        }

19 View Source File : AdminBase.cs
License : Apache License 2.0
Project Creator : oorz

public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            //1.验证是否登录
            //2.验证菜单权限
            //3.验证按钮权限
            //在action执行之前

            //验证是否登录
            if (!IsAdminLogin())
            {
                string msg = string.Format("未登录或登录超时,请重新登录!");
                filterContext.Result = new RedirectResult("~/ad_min/login?msg=" + WebUtility.UrlEncode(msg));
                return;
            }

            //判断是否加有SkipAdmin标签
            var skipAuthorize = filterContext.ActionDescriptor.FilterDescriptors.Where(a => a.Filter is SkipAdminAuthorizeAttribute).Any();
            if (!skipAuthorize)
            {
                //是否系统管理文件夹里文件,Areas》ad_min
                var isPermission = false;
                //获取controller和action
                var route = filterContext.RouteData.Values;

                string strArea = route["area"].ToString();//获取区域的名字,ad_min区域下的都需要权限验证
                if (strArea != null && strArea.Equals("ad_min"))
                {
                    isPermission = true;
                }
                //需要验证权限
                if (isPermission)
                {
                    var currController = route["controller"].ToString();
                    var curraction = route["action"].ToString();
                    var exceptCtr = UtilConf.Configuration["Site:exceptCtr"].Replace(",", ",");//防止中文逗号
                    var exceptAction = UtilConf.Configuration["Site:exceptAction"].Replace(",", ",");//防止中文逗号
                    //判断是否有例外控制器或Action校验是否例外,跳过验证
                    if (!exceptCtr.Contains(currController.ToLower()) && !exceptAction.Contains(curraction.ToLower()))
                    {
                        //验证菜单权限
                        //验证按钮权限
                        //自定义方法属性
                        try
                        {
                            if (siteAdminInfo.RoleType != 1)//超管拥有所有权限
                            {
                                //获取属性
                                NavAttr actionAttr = filterContext.ActionDescriptor.FilterDescriptors.Where(a => a.Filter is NavAttr).Select(a => a.Filter).FirstOrDefault() as NavAttr;
                                string strNavName = string.Empty;
                                string strActionType = string.Empty;
                                if (actionAttr == null)
                                {
                                    actionAttr = filterContext.ActionDescriptor.FilterDescriptors.GetType().GetCustomAttributes<NavAttr>().FirstOrDefault() as NavAttr;
                                }
                                if (actionAttr != null)
                                {
                                    strNavName = actionAttr.NavName;
                                    strActionType = actionAttr.ActionType;
                                }
                                //获取参数,由于action在mvc中属于关键词,所以使用act当作操作方式参数
                                string paramAction = "";
                                if (Request.Method.ToLower() == "get" || Request.QueryString.HasValue)//判断是get请求
                                {
                                    paramAction = Request.Query["act"].ToString();
                                    if (string.IsNullOrEmpty(paramAction))
                                    {
                                        if (route["act"] != null)
                                        {
                                            paramAction = route["act"].ToString();
                                        }
                                    }
                                }
                                else
                                {
                                    paramAction = Request.Form["act"].ToString();//post请求,只有post下且有参数才可以用写Request.Form,否则报异常。
                                    if (string.IsNullOrEmpty(paramAction))
                                    {
                                        if (route["act"] != null)
                                        {
                                            paramAction = route["act"].ToString();
                                        }
                                    }
                                }
                                if (!ChkPermission(siteAdminInfo.RoleId, currController, curraction, strNavName, strActionType, paramAction))
                                {
                                    TempData["Permission"] = "您没有管理" + "currController:" + currController + ";curraction:" + curraction + ";NavName:" + strNavName + ";strActionType:" + strActionType + ";paramAction:" + paramAction + "页面的权限,请联系管理员!";
                                    filterContext.Result = new RedirectResult("~/ad_min/Home/Index");
                                    return;
                                    //返回固定错误json
                                }
                                else
                                {
                                    TempData["Permission"] = null;
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
            }
        }

19 View Source File : BaggagePropagator.cs
License : Apache License 2.0
Project Creator : open-telemetry

public override void Inject<T>(PropagationContext context, T carrier, Action<T, string, string> setter)
        {
            if (carrier == null)
            {
                OpenTelemetryApiEventSource.Log.FailedToInjectBaggage(nameof(BaggagePropagator), "null carrier");
                return;
            }

            if (setter == null)
            {
                OpenTelemetryApiEventSource.Log.FailedToInjectBaggage(nameof(BaggagePropagator), "null setter");
                return;
            }

            using var e = context.Baggage.GetEnumerator();

            if (e.MoveNext() == true)
            {
                int itemCount = 0;
                StringBuilder baggage = new StringBuilder();
                do
                {
                    KeyValuePair<string, string> item = e.Current;
                    if (string.IsNullOrEmpty(item.Value))
                    {
                        continue;
                    }

                    baggage.Append(WebUtility.UrlEncode(item.Key)).Append('=').Append(WebUtility.UrlEncode(item.Value)).Append(',');
                }
                while (e.MoveNext() && ++itemCount < MaxBaggageItems && baggage.Length < MaxBaggageLength);
                baggage.Remove(baggage.Length - 1, 1);
                setter(carrier, BaggageHeaderName, baggage.ToString());
            }
        }

19 View Source File : BaggagePropagatorTest.cs
License : Apache License 2.0
Project Creator : open-telemetry

[Fact]
        public void ValidateSpecialCharsBaggageExtraction()
        {
            var encodedKey = WebUtility.UrlEncode("key2");
            var encodedValue = WebUtility.UrlEncode("!x_x,x-x&x(x\");:");
            var escapedKey = Uri.EscapeDataString("key()3");
            var escapedValue = Uri.EscapeDataString("value()!&;:");

            replacedert.Equal("key2", encodedKey);
            replacedert.Equal("!x_x%2Cx-x%26x(x%22)%3B%3A", encodedValue);
            replacedert.Equal("key%28%293", escapedKey);
            replacedert.Equal("value%28%29%21%26%3B%3A", escapedValue);

            var initialBaggage = $"key+1=value+1,{encodedKey}={encodedValue},{escapedKey}={escapedValue}";
            var carrier = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>(BaggagePropagator.BaggageHeaderName, initialBaggage),
            };

            var propagationContext = this.baggage.Extract(default, carrier, GetterList);

            replacedert.False(propagationContext == default);
            replacedert.True(propagationContext.ActivityContext == default);

            replacedert.Equal(3, propagationContext.Baggage.Count);

            var actualBaggage = propagationContext.Baggage.GetBaggage();

            replacedert.Equal(3, actualBaggage.Count);

            replacedert.True(actualBaggage.ContainsKey("key 1"));
            replacedert.Equal("value 1", actualBaggage["key 1"]);

            replacedert.True(actualBaggage.ContainsKey("key2"));
            replacedert.Equal("!x_x,x-x&x(x\");:", actualBaggage["key2"]);

            replacedert.True(actualBaggage.ContainsKey("key()3"));
            replacedert.Equal("value()!&;:", actualBaggage["key()3"]);
        }

19 View Source File : FileService.cs
License : MIT License
Project Creator : oqtane

public async Task<List<File>> GetFilesAsync(int siteId, string folderPath)
        {
            if (!(folderPath.EndsWith(System.IO.Path.DirectorySeparatorChar) || folderPath.EndsWith(System.IO.Path.AltDirectorySeparatorChar)))
            {
                folderPath = Utilities.PathCombine(folderPath, System.IO.Path.DirectorySeparatorChar.ToString());
            }

            var path = WebUtility.UrlEncode(folderPath);

            return await GetJsonAsync<List<File>>($"{Apiurl}/{siteId}/{path}");
        }

19 View Source File : FileService.cs
License : MIT License
Project Creator : oqtane

public async Task<File> UploadFileAsync(string url, int folderId, string name)
        {
            return await GetJsonAsync<File>($"{Apiurl}/upload?url={WebUtility.UrlEncode(url)}&folderid={folderId}&name={name}");
        }

19 View Source File : FolderService.cs
License : MIT License
Project Creator : oqtane

public async Task<Folder> GetFolderAsync(int siteId, [NotNull] string folderPath)
        {
            var path = WebUtility.UrlEncode(folderPath);
            return await GetJsonAsync<Folder>($"{ApiUrl}/{siteId}/{path}");
        }

19 View Source File : InstallationService.cs
License : MIT License
Project Creator : oqtane

public async Task<Installation> IsInstalled()
        {
            var path = new Uri(_navigationManager.Uri).LocalPath.Substring(1);            
            return await GetJsonAsync<Installation>($"{ApiUrl}/installed/?path={WebUtility.UrlEncode(path)}");
        }

19 View Source File : InstallationService.cs
License : MIT License
Project Creator : oqtane

public async Task RegisterAsync(string email)
        {
            await PostJsonAsync($"{ApiUrl}/register?email={WebUtility.UrlEncode(email)}", true);
        }

19 View Source File : PackageService.cs
License : MIT License
Project Creator : oqtane

public async Task<List<Package>> GetPackagesAsync(string type, string search, string price, string package)
        {
            return await GetJsonAsync<List<Package>>($"{Apiurl}?type={type}&search={WebUtility.UrlEncode(search)}&price={price}&package={package}");
        }

19 View Source File : PageService.cs
License : MIT License
Project Creator : oqtane

public async Task<Page> GetPageAsync(string path, int siteId)
        {
            try
            {
                return await GetJsonAsync<Page>($"{Apiurl}/path/{siteId}?path={WebUtility.UrlEncode(path)}");
            }
            catch
            {
                return null;
            }
        }

19 View Source File : InstallationController.cs
License : MIT License
Project Creator : oqtane

private async Task RegisterContact(string email)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Referer", HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value);
                    client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(Constants.PackageId, Constants.Version));
                    Uri uri = new Uri(Constants.PackageRegistryUrl + $"/api/registry/contact/?id={_configManager.GetInstallationId()}&email={WebUtility.UrlEncode(email)}");
                    var response = await client.GetAsync(uri).ConfigureAwait(false);
                }
            }
            catch
            {
                // error calling registry service
            }
        }

19 View Source File : UserController.cs
License : MIT License
Project Creator : oqtane

[HttpPost("forgot")]
        public async Task Forgot([FromBody] User user)
        {
            if (ModelState.IsValid)
            {
                IdenreplacedyUser idenreplacedyuser = await _idenreplacedyUserManager.FindByNameAsync(user.Username);
                if (idenreplacedyuser != null)
                {
                    string token = await _idenreplacedyUserManager.GeneratePreplacedwordResetTokenAsync(idenreplacedyuser);
                    string url = HttpContext.Request.Scheme + "://" + _alias.Name + "/reset?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
                    string body = "Dear " + user.DisplayName + ",\n\nPlease Click The Link Displayed Below To Reset Your Preplacedword:\n\n" + url + "\n\nThank You!";
                    var notification = new Notification(user.SiteId, null, user, "User Preplacedword Reset", body, null);
                    _notifications.AddNotification(notification);
                    _logger.Log(LogLevel.Information, this, LogFunction.Security, "Preplacedword Reset Notification Sent For {Username}", user.Username);
                }
                else
                {
                    _logger.Log(LogLevel.Error, this, LogFunction.Security, "Preplacedword Reset Notification Failed For {Username}", user.Username);
                }
            }
        }

19 View Source File : UserController.cs
License : MIT License
Project Creator : oqtane

private async Task<User> CreateUser(User user)
        {
            User newUser = null;

            bool verified;
            bool allowregistration;
            if (User.IsInRole(RoleNames.Admin))
            {
                verified = true;
                allowregistration = true;
            }
            else
            {
                verified = false;
                allowregistration = _sites.GetSite(user.SiteId).AllowRegistration;
            }

            if (allowregistration)
            {
                IdenreplacedyUser idenreplacedyuser = await _idenreplacedyUserManager.FindByNameAsync(user.Username);
                if (idenreplacedyuser == null)
                {
                    idenreplacedyuser = new IdenreplacedyUser();
                    idenreplacedyuser.UserName = user.Username;
                    idenreplacedyuser.Email = user.Email;
                    idenreplacedyuser.EmailConfirmed = verified;
                    var result = await _idenreplacedyUserManager.CreateAsync(idenreplacedyuser, user.Preplacedword);
                    if (result.Succeeded)
                    {
                        user.LastLoginOn = null;
                        user.LastIPAddress = "";
                        newUser = _users.AddUser(user);
                        if (!verified)
                        {
                            string token = await _idenreplacedyUserManager.GenerateEmailConfirmationTokenAsync(idenreplacedyuser);
                            string url = HttpContext.Request.Scheme + "://" + _alias.Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
                            string body = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!";
                            var notification = new Notification(user.SiteId, null, newUser, "User Account Verification", body, null);
                            _notifications.AddNotification(notification);
                        }

                        // add folder for user
                        Folder folder = _folders.GetFolder(user.SiteId, Utilities.PathCombine("Users",Path.DirectorySeparatorChar.ToString()));
                        if (folder != null)
                        {
                            _folders.AddFolder(new Folder
                            {
                                SiteId = folder.SiteId,
                                ParentId = folder.FolderId,
                                Name = "My Folder",
                                Type = FolderTypes.Private,
                                Path = Utilities.PathCombine(folder.Path, newUser.UserId.ToString(), Path.DirectorySeparatorChar.ToString()),
                                Order = 1,
                                ImageSizes = "",
                                Capacity = Constants.UserFolderCapacity,
                                IsSystem = true,
                                Permissions = new List<Permission>
                                {
                                    new Permission(PermissionNames.Browse, newUser.UserId, true),
                                    new Permission(PermissionNames.View, RoleNames.Everyone, true),
                                    new Permission(PermissionNames.Edit, newUser.UserId, true)
                                }.EncodePermissions()
                            }) ;
                        }
                    }
                }
                else
                {
                    var result = await _idenreplacedySignInManager.CheckPreplacedwordSignInAsync(idenreplacedyuser, user.Preplacedword, false);
                    if (result.Succeeded)
                    {
                        newUser = _users.GetUser(user.Username);
                    }
                }

                if (newUser != null)
                {
                    // add auto replacedigned roles to user for site
                    List<Role> roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoreplacedigned).ToList();
                    foreach (Role role in roles)
                    {
                        UserRole userrole = new UserRole();
                        userrole.UserId = newUser.UserId;
                        userrole.RoleId = role.RoleId;
                        userrole.EffectiveDate = null;
                        userrole.ExpiryDate = null;
                        _userRoles.AddUserRole(userrole);
                    }
                }

                if (newUser != null)
                {
                    newUser.Preplacedword = ""; // remove sensitive information
                    _logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser);
                }
            }
            else
            {
                _logger.Log(user.SiteId, LogLevel.Error, this, LogFunction.Create, "User Registration Is Not Enabled For Site. User Was Not Added {User}", user);
            }

            return newUser;
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual void Initialize()
        {
            // Initialize serialization settings

            // Initialize query client
            _httpQueryClient = _factory?.CreateClient() ?? new HttpClient();
            _httpQueryClient.DefaultRequestHeaders.Accept.Clear();
            _httpQueryClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            if (_options.UseCdn)
            {
                _httpQueryClient.BaseAddress = new Uri($"https://{WebUtility.UrlEncode(_options.ProjectId)}.apicdn.sanity.io/{_options.ApiVersion}/");
            }
            else
            {
                _httpQueryClient.BaseAddress = new Uri($"https://{WebUtility.UrlEncode(_options.ProjectId)}.api.sanity.io/{_options.ApiVersion}/");
            }
            if (!string.IsNullOrEmpty(_options.Token) && !_options.UseCdn)
            {
                _httpQueryClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _options.Token);
            }

            // Initialize client for non-query requests (i.e. requests than never use CDN)
            if (!_options.UseCdn)
            {
                _httpClient = _httpQueryClient;
            }
            else
            {
                _httpClient = _factory?.CreateClient() ?? new HttpClient();
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.BaseAddress = new Uri($"https://{WebUtility.UrlEncode(_options.ProjectId)}.api.sanity.io/{_options.ApiVersion}/");
                if (!string.IsNullOrEmpty(_options.Token))
                {
                    _httpQueryClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _options.Token);
                }
            }

        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityQueryResponse<TResult>> FetchAsync<TResult>(string query, object parameters = null, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException("Query cannot be empty", nameof(query));
            }
            var oQuery = new SanityQuery
            {
                Query = query,
                Params = parameters
            };
            HttpResponseMessage response = null;
            if (_options.UseCdn)
            {
                // CDN only supports GET requests
                var url = $"data/query/{WebUtility.UrlEncode(_options.Dataset)}?query={WebUtility.UrlEncode(query ?? "")}";
                if (parameters != null)
                {
                    //TODO: Add support for parameters
                }
                response = await _httpQueryClient.GetAsync(url, cancellationToken);
            }
            else
            {
                // Preferred method is POST
                var json = new StringContent(JsonConvert.SerializeObject(oQuery, Formatting.None, SerializerSettings), Encoding.UTF8, "application/json");
                response = await _httpQueryClient.PostAsync($"data/query/{WebUtility.UrlEncode(_options.Dataset)}", json, cancellationToken).ConfigureAwait(false);
            }

            return await HandleHttpResponseAsync<SanityQueryResponse<TResult>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityQueryResponse<TResult>> FetchAsync<TResult>(string query, object parameters = null, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException("Query cannot be empty", nameof(query));
            }
            var oQuery = new SanityQuery
            {
                Query = query,
                Params = parameters
            };
            HttpResponseMessage response = null;
            if (_options.UseCdn)
            {
                // CDN only supports GET requests
                var url = $"data/query/{WebUtility.UrlEncode(_options.Dataset)}?query={WebUtility.UrlEncode(query ?? "")}";
                if (parameters != null)
                {
                    //TODO: Add support for parameters
                }
                response = await _httpQueryClient.GetAsync(url, cancellationToken);
            }
            else
            {
                // Preferred method is POST
                var json = new StringContent(JsonConvert.SerializeObject(oQuery, Formatting.None, SerializerSettings), Encoding.UTF8, "application/json");
                response = await _httpQueryClient.PostAsync($"data/query/{WebUtility.UrlEncode(_options.Dataset)}", json, cancellationToken).ConfigureAwait(false);
            }

            return await HandleHttpResponseAsync<SanityQueryResponse<TResult>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityDoreplacedentsResponse<TDoc>> GetDoreplacedentAsync<TDoc>(string id, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException("Id cannot be empty", nameof(id));
            }
            var response = await _httpQueryClient.GetAsync($"data/doc/{WebUtility.UrlEncode(_options.Dataset)}/{WebUtility.UrlEncode(id)}", cancellationToken).ConfigureAwait(false);
            return await HandleHttpResponseAsync<SanityDoreplacedentsResponse<TDoc>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityDoreplacedentsResponse<TDoc>> GetDoreplacedentAsync<TDoc>(string id, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException("Id cannot be empty", nameof(id));
            }
            var response = await _httpQueryClient.GetAsync($"data/doc/{WebUtility.UrlEncode(_options.Dataset)}/{WebUtility.UrlEncode(id)}", cancellationToken).ConfigureAwait(false);
            return await HandleHttpResponseAsync<SanityDoreplacedentsResponse<TDoc>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityDoreplacedentResponse<SanityImagereplacedet>> UploadImageAsync(Stream stream, string fileName, string contentType = null, string label = null, CancellationToken cancellationToken = default)
        {
            var query = new List<string>();
            if (!string.IsNullOrEmpty(fileName))
            {
                query.Add($"filename={WebUtility.UrlEncode(fileName)}");
            }
            if (!string.IsNullOrEmpty(label))
            {
                query.Add($"label={WebUtility.UrlEncode(label)}");
            }
            var uri = $"replacedets/images/{WebUtility.UrlEncode(_options.Dataset)}{(query.Count > 0 ? "?" + query.Aggregate((c,n) => c + "&" + n) : "")}";
            var request = new HttpRequestMessage(HttpMethod.Post, uri);

            request.Content = new StreamContent(stream);
            if (!string.IsNullOrEmpty(contentType))
            {
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            }           

            var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
            return await HandleHttpResponseAsync<SanityDoreplacedentResponse<SanityImagereplacedet>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityDoreplacedentResponse<SanityImagereplacedet>> UploadImageAsync(Stream stream, string fileName, string contentType = null, string label = null, CancellationToken cancellationToken = default)
        {
            var query = new List<string>();
            if (!string.IsNullOrEmpty(fileName))
            {
                query.Add($"filename={WebUtility.UrlEncode(fileName)}");
            }
            if (!string.IsNullOrEmpty(label))
            {
                query.Add($"label={WebUtility.UrlEncode(label)}");
            }
            var uri = $"replacedets/images/{WebUtility.UrlEncode(_options.Dataset)}{(query.Count > 0 ? "?" + query.Aggregate((c,n) => c + "&" + n) : "")}";
            var request = new HttpRequestMessage(HttpMethod.Post, uri);

            request.Content = new StreamContent(stream);
            if (!string.IsNullOrEmpty(contentType))
            {
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            }           

            var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
            return await HandleHttpResponseAsync<SanityDoreplacedentResponse<SanityImagereplacedet>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityDoreplacedentResponse<SanityFilereplacedet>> UploadFileAsync(Stream stream, string fileName, string contentType = null, string label = null, CancellationToken cancellationToken = default)
        {
            var query = new List<string>();
            if (!string.IsNullOrEmpty(fileName))
            {
                query.Add($"filename={WebUtility.UrlEncode(fileName)}");
            }
            if (!string.IsNullOrEmpty(label))
            {
                query.Add($"label={WebUtility.UrlEncode(label)}");
            }
            var uri = $"replacedets/files/{WebUtility.UrlEncode(_options.Dataset)}{(query.Count > 0 ? "?" + query.Aggregate((c, n) => c + "&" + n) : "")}";
            var request = new HttpRequestMessage(HttpMethod.Post, uri);

            request.Content = new StreamContent(stream);
            if (!string.IsNullOrEmpty(contentType))
            {
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            }

            var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
            return await HandleHttpResponseAsync<SanityDoreplacedentResponse<SanityFilereplacedet>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

public virtual async Task<SanityDoreplacedentResponse<SanityFilereplacedet>> UploadFileAsync(Stream stream, string fileName, string contentType = null, string label = null, CancellationToken cancellationToken = default)
        {
            var query = new List<string>();
            if (!string.IsNullOrEmpty(fileName))
            {
                query.Add($"filename={WebUtility.UrlEncode(fileName)}");
            }
            if (!string.IsNullOrEmpty(label))
            {
                query.Add($"label={WebUtility.UrlEncode(label)}");
            }
            var uri = $"replacedets/files/{WebUtility.UrlEncode(_options.Dataset)}{(query.Count > 0 ? "?" + query.Aggregate((c, n) => c + "&" + n) : "")}";
            var request = new HttpRequestMessage(HttpMethod.Post, uri);

            request.Content = new StreamContent(stream);
            if (!string.IsNullOrEmpty(contentType))
            {
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            }

            var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
            return await HandleHttpResponseAsync<SanityDoreplacedentResponse<SanityFilereplacedet>>(response).ConfigureAwait(false);
        }

19 View Source File : SanityClient.cs
License : MIT License
Project Creator : oslofjord

protected virtual async Task<TResult> CommitMutationsInternalAsync<TResult>(object mutations, bool returnIds = false, bool returnDoreplacedents = false, SanityMutationVisibility visibility = SanityMutationVisibility.Sync, CancellationToken cancellationToken = default)
        {
            if (mutations == null)
            {
                throw new ArgumentNullException(nameof(mutations));
            }

            var json = mutations is string ? mutations as string : 
                       mutations is SanityMutationBuilder ? ((SanityMutationBuilder)mutations).Build(SerializerSettings) : 
                       JsonConvert.SerializeObject(mutations, Formatting.None, SerializerSettings);

            var response = await _httpClient.PostAsync($"data/mutate/{WebUtility.UrlEncode(_options.Dataset)}?returnIds={returnIds.ToString().ToLower()}&returnDoreplacedents={returnDoreplacedents.ToString().ToLower()}&visibility={visibility.ToString().ToLower()}", new StringContent(json, Encoding.UTF8, "application/json"), cancellationToken).ConfigureAwait(false);
            return await HandleHttpResponseAsync<TResult>(response).ConfigureAwait(false);
        }

19 View Source File : Projects.cs
License : MIT License
Project Creator : pauldotknopf

public IProject Project(string fullName)
        {
            ProjectId = WebUtility.UrlEncode(fullName);
            return this;
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : pawotter

internal static string UrlEncoded(this object obj)
        {
            return WebUtility.UrlEncode(obj.ToString());
        }

19 View Source File : TokenAuthController.cs
License : MIT License
Project Creator : personball

[Route("WechatH5Auth")]
        [HttpGet]
        public IActionResult WechatH5Auth(string targetUrl)
        {
            var appId = _appConfiguration["Authentication:WechatH5:AppId"];
            Uri uriResult;
            Uri.TryCreate(new Uri(_appConfiguration["App:ServerRootAddress"]), "/api/TokenAuth/WechatH5AuthCallback/WechatH5AuthCallback", out uriResult);
            //var redirect = WebUtility.UrlEncode($"{_appConfiguration["App:ServerRootAddress"]}/api/TokenAuth/WechatH5AuthCallback/WechatH5AuthCallback?targetUrl={targetUrl}");
            var redirect = WebUtility.UrlEncode($"{uriResult.AbsoluteUri}?targetUrl={WebUtility.UrlEncode(targetUrl)}");
            var scope = "snsapi_userinfo";
            var state = WebUtility.UrlEncode(SimpleStringCipher.Instance.Encrypt($"{DateTime.Now.AddMinutes(5).ToString()}", AppConsts.DefaultPreplacedPhrase));//用5分钟后的时间戳对称加密下

            Logger.Debug($"WechatH5Auth:state:{state}");

            return Redirect($"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&redirect_uri={redirect}&response_type=code&scope={scope}&state={state}#wechat_redirect");
        }

19 View Source File : TokenAuthController.cs
License : MIT License
Project Creator : personball

[Route("WechatH5Auth")]
        [HttpGet]
        public IActionResult WechatH5Auth(string targetUrl)
        {
            var appId = _appConfiguration["Authentication:WechatH5:AppId"];
            Uri uriResult;
            Uri.TryCreate(new Uri(_appConfiguration["App:ServerRootAddress"]), "/api/TokenAuth/WechatH5AuthCallback/WechatH5AuthCallback", out uriResult);
            //var redirect = WebUtility.UrlEncode($"{_appConfiguration["App:ServerRootAddress"]}/api/TokenAuth/WechatH5AuthCallback/WechatH5AuthCallback?targetUrl={targetUrl}");
            var redirect = WebUtility.UrlEncode($"{uriResult.AbsoluteUri}?targetUrl={WebUtility.UrlEncode(targetUrl)}");
            var scope = "snsapi_userinfo";
            var state = WebUtility.UrlEncode(SimpleStringCipher.Instance.Encrypt($"{DateTime.Now.AddMinutes(5).ToString()}", AppConsts.DefaultPreplacedPhrase));//用5分钟后的时间戳对称加密下

            Logger.Debug($"WechatH5Auth:state:{state}");

            return Redirect($"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&redirect_uri={redirect}&response_type=code&scope={scope}&state={state}#wechat_redirect");
        }

19 View Source File : TokenAuthController.cs
License : MIT License
Project Creator : personball

[Route("WechatH5AuthCallback")]
        [HttpGet]
        public IActionResult WechatH5AuthCallback(string code, string state, string targetUrl)
        {
            Logger.Debug($"WechatH5AuthCallback:state:{state}");

            //state验证
            var expiredState = DateTime.Now.AddMinutes(-1);
            DateTime.TryParse(SimpleStringCipher.Instance.Decrypt(state, AppConsts.DefaultPreplacedPhrase), out expiredState);
            if (expiredState < DateTime.Now)
            {
                throw new AbpProjectNameBusinessException(ErrorCode.Forbidden);
            }

            //拿code直接加盐对称加密丢给前端,再让前端调用External Login接口换BearerToken
            var encryptedCode = WebUtility.UrlEncode(SimpleStringCipher.Instance.Encrypt($"{code}|{DateTime.Now.AddMinutes(5).ToString()}", AppConsts.DefaultPreplacedPhrase));

            Logger.Debug($"WechatH5AuthCallback:encryptedCode:{encryptedCode}");

            return Redirect($"{targetUrl}?encryptedCode={encryptedCode}");
        }

19 View Source File : MacGardenController.cs
License : MIT License
Project Creator : pgodwin

internal DirectoryResult Search(string search)
        {
            var searchUrl = "http://macintoshgarden.org/search/node/" + WebUtility.UrlEncode(search + " type:app,game");
            var searchResults = new Models.SearchResults(searchUrl);
            return new Results.SearchResult(searchResults);
        }

19 View Source File : DigitalstromClientBase.cs
License : MIT License
Project Creator : philipdaubmeier

private async Task<Uri> BuildAbsoluteUri(Uri relativeUri)
        {
            var baseUri = await GetBaseUri();
            if (baseUri is null)
                throw new IOException("No base uri was given");
            else if (_baseUris.CurrentHasAuthIncluded())
                return new Uri($"{baseUri}{WebUtility.UrlEncode(relativeUri.ToString())}");
            else
                return new Uri(baseUri, relativeUri);
        }

19 View Source File : ConversionExtensions.cs
License : MIT License
Project Creator : philipdaubmeier

public static string ToFilterTime(this DateTime time)
        {
            return WebUtility.UrlEncode(time.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture));
        }

19 View Source File : WebTests.cs
License : MIT License
Project Creator : PhilShishov

[Theory]
        [InlineData("/account/email")]
        [InlineData("/account/change-preplacedword")]
        [InlineData("/account/personal-data")]
        [InlineData("/userpanel")]
        [InlineData("/funds")]
        [InlineData("/subfunds")]
        [InlineData("/shareclreplacedes")]
        [InlineData("/sc/new")]
        [InlineData("/sc/edit/1/2020-11-09")]
        [InlineData("/reports/Fund/aum")]
        [InlineData("/reports/SubFund/aum")]
        [InlineData("/agreements/Fund")]
        [InlineData("/Admin/Admin/All")]
        [InlineData("/Admin/Admin/Create")]
        public async Task AccessPrivatePage_WithUnauthorizedUser_ShoudRedirectToLoginPage(string url)
        {
            var client = server.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
            var response = await client.GetAsync(url);

            replacedert.Equal(HttpStatusCode.Redirect, response.StatusCode);
            string expectedUrl = $"/Account/Login?ReturnUrl={WebUtility.UrlEncode(url)}";
            replacedert.Contains(expectedUrl, response.Headers.Location.ToString());
        }

19 View Source File : Telemetry.cs
License : Mozilla Public License 2.0
Project Creator : phw198

public static void Send(replacedytics.Category category, replacedytics.Action action, String label) {
            String cid = GoogleOgcs.Authenticator.HashedGmailAccount ?? "1";
            String basereplacedyticsUrl = "https://www.google-replacedytics.com/collect?v=1&t=event&tid=UA-19426033-4&aip=1&cid=" + cid;

            if (action == replacedytics.Action.debug) {
                label = "v" + System.Windows.Forms.Application.ProductVersion + ";" + label;
            }
            String replacedyticsUrl = basereplacedyticsUrl + "&ec=" + category.ToString() + "&ea=" + action.ToString() + "&el=" + System.Net.WebUtility.UrlEncode(label);
            log.Debug("Retrieving URL: " + replacedyticsUrl);
            
            if (Settings.Instance.TelemetryDisabled || Program.InDeveloperMode) {
                log.Debug("Telemetry is disabled.");
                return;
            }

            Extensions.OgcsWebClient wc = new Extensions.OgcsWebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(sendTelemetry_completed);
            wc.DownloadStringAsync(new Uri(replacedyticsUrl), replacedyticsUrl);
        }

19 View Source File : Web.cs
License : MIT License
Project Creator : pnp

private static ApiCall BuildGetFolderByRelativeUrlApiCall(string serverRelativeUrl)
        {
            // NOTE WebUtility encode spaces to "+" instead of %20
            string encodedServerRelativeUrl = WebUtility.UrlEncode(serverRelativeUrl.Replace("'", "''")).Replace("+", "%20");
            var apiCall = new ApiCall($"_api/Web/getFolderByServerRelativePath(decodedUrl='{encodedServerRelativeUrl}')", ApiType.SPORest);
            return apiCall;
        }

19 View Source File : Web.cs
License : MIT License
Project Creator : pnp

private static ApiCall BuildGetFileByRelativeUrlApiCall(string serverRelativeUrl)
        {
            // NOTE WebUtility encode spaces to "+" instead of %20
            string encodedServerRelativeUrl = WebUtility.UrlEncode(serverRelativeUrl.Replace("'", "''")).Replace("+", "%20");
            var apiCall = new ApiCall($"_api/Web/getFileByServerRelativePath(decodedUrl='{encodedServerRelativeUrl}')", ApiType.SPORest);
            return apiCall;
        }

19 View Source File : AttachmentCollection.cs
License : MIT License
Project Creator : pnp

private static async Task<Attachment> FileUpload(Attachment newFile, Stream content)
        {
            var encodedServerFileName = WebUtility.UrlEncode(newFile.FileName.Replace("'", "''")).Replace("+", "%20");
            string fileCreateRequest = $"_api/web/lists/getbyid(guid'{{List.Id}}')/items({{Parent.Id}})/attachmentfiles/addusingpath(decodedUrl='{encodedServerFileName}')";
            var api = new ApiCall(fileCreateRequest, ApiType.SPORest)
            {
                Interactive = true,
                BinaryBody = ToByteArray(content)
            };
            await newFile.RequestAsync(api, HttpMethod.Post).ConfigureAwait(false);
            return newFile;
        }

19 View Source File : FileCollection.cs
License : MIT License
Project Creator : pnp

public async Task<IFile> AddTemplateFileAsync(string serverRelativePageName, TemplateFileType templateFileType)
        {
            if (string.IsNullOrEmpty(serverRelativePageName))
            {
                throw new ArgumentNullException(nameof(serverRelativePageName));
            }

            // Replace # with - as AddTemplateFile cannot handle an # in the name. This replacement is the same behavior than the SharePoint UI does
            var encodedServerRelativePageName = WebUtility.UrlEncode(serverRelativePageName.Replace("'", "''").Replace("#", "-")).Replace("+", "%20");
            var newFile = CreateNewAndAdd() as File;
            string fileCreateRequest = $"_api/web/getFolderById('{{Parent.Id}}')/files/AddTemplateFile(urlOfFile='{encodedServerRelativePageName}',templateFileType={(int)templateFileType})";
            var api = new ApiCall(fileCreateRequest, ApiType.SPORest);
            await newFile.RequestAsync(api, HttpMethod.Post).ConfigureAwait(false);
            return newFile;
        }

19 View Source File : FileCollection.cs
License : MIT License
Project Creator : pnp

private static async Task<File> FileUpload(File newFile, Stream content, bool overwrite)
        {
            var encodedServerFileName = WebUtility.UrlEncode(newFile.Name.Replace("'", "''")).Replace("+", "%20");
            string fileCreateRequest = $"_api/web/getFolderById('{{Parent.Id}}')/files/addusingpath(decodedUrl='{encodedServerFileName}',overwrite={overwrite.ToString().ToLowerInvariant()})";
            var api = new ApiCall(fileCreateRequest, ApiType.SPORest)
            {
                Interactive = true,
                BinaryBody = ToByteArray(content)
            };
            await newFile.RequestAsync(api, HttpMethod.Post).ConfigureAwait(false);
            return newFile;
        }

19 View Source File : File.cs
License : MIT License
Project Creator : pnp

private ApiCall GetCopyToSameSiteApiCall(string destinationUrl, bool overwrite)
        {
            var enreplacedyInfo = EnreplacedyManager.GetClreplacedInfo(GetType(), this);
            // NOTE WebUtility encode spaces to "+" instead of %20
            string encodedDestinationUrl = WebUtility.UrlEncode(destinationUrl).Replace("+", "%20").Replace("/", "%2F");
            string copyToEndpointUrl = $"{enreplacedyInfo.SharePointUri}/copyTo(strnewurl='{encodedDestinationUrl}', boverwrite={overwrite.ToString().ToLower()})";

            return new ApiCall(copyToEndpointUrl, ApiType.SPORest);
        }

19 View Source File : File.cs
License : MIT License
Project Creator : pnp

private ApiCall GetMoveToSameSiteApiCall(string destinationUrl, MoveOperations moveOperations)
        {
            var enreplacedyInfo = EnreplacedyManager.GetClreplacedInfo(GetType(), this);
            // NOTE WebUtility encode spaces to "+" instead of %20
            string encodedDestinationUrl = WebUtility.UrlEncode(destinationUrl).Replace("+", "%20").Replace("/", "%2F");
            string moveToEndpointUrl = $"{enreplacedyInfo.SharePointUri}/moveTo(newurl='{encodedDestinationUrl}', flags={(int)moveOperations})";

            return new ApiCall(moveToEndpointUrl, ApiType.SPORest);
        }

19 View Source File : AddSPLibTabActivity.cs
License : MIT License
Project Creator : pnp

protected static async Task AddConfiguredLibTabsToChannel(string groupId, string channelId, string targetSiteOrSiteCollectionUrl, GraphServiceClient client, TeamsTabService tabService, List<string> librariesNames, Regex executer)
        {
            bool validation(string sectionName, TeamsTab x) => x.DisplayName == sectionName;
            var hostNameAndPath = getSiteHostNameAndPath(executer, targetSiteOrSiteCollectionUrl);
            var site = await getTargetSite(client, hostNameAndPath);
            foreach (var libraryName in librariesNames)
            {
                var libraryServerRelativeUrl = await getTargetLibrary(client, libraryName, hostNameAndPath.Item1, site);
                if (!await tabService.DoesTabExist(groupId, channelId, (x) => validation(libraryName, x)) && !string.IsNullOrEmpty(libraryServerRelativeUrl))
                    await tabService.AddTab(groupId, channelId, libraryName, getTabConfiguration($"https://{hostNameAndPath.Item1}{hostNameAndPath.Item2}", $"/{WebUtility.UrlEncode(libraryName)}"));
            }
        }

19 View Source File : Entry.cs
License : MIT License
Project Creator : poppastring

public static string InternalCompressreplacedle(string replacedleParam)
		{
			if (replacedleParam == null || replacedleParam.Length == 0)
			{
				return String.Empty;
			}

			StringBuilder retVal = new StringBuilder(replacedleParam.Length);

			bool pendingSpace = false;
			bool tag = false;

			for (int i = 0; i < replacedleParam.Length; ++i)
			{
				char c = replacedleParam[i];

				if (tag)
				{
					if (c == '>')
					{
						tag = false;
					}
				}
				else if (c == '<')
				{
					// Discard everything between '<' and '>', inclusive.
					// If no '>', just discard the '<'.
					tag = (replacedleParam.IndexOf('>', i) >= 0);
				}

					// Per RFC 2396 (URI syntax):
					//  delims   = "<" | ">" | "#" | "%" | <">
					//  reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
					// These characters should not appear in a URL
				else if ("#%\";/?:@&=$,".IndexOf(c) >= 0)
				{
					continue;
				}

				else if (char.IsWhiteSpace(c))
				{
					pendingSpace = true;
				}

					// The marks may appear in URLs
					//  mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
					// as may all alphanumerics. (Tilde gets mangled by UrlEncode).
					// Here we are more lenient than RFC 2396, as we allow
					// all Unicode alphanumerics, not just the US-ASCII ones.
					// SDH: Update: it's really safer and maintains more permalinks if we stick with A-Za-z0-9.
				else if (char.IsLetterOrDigit(c) /* ||  "-_.!~*'()".IndexOf(c) >= 0 */)
				{
					if (pendingSpace)
					{
						// Discard leading spaces
						if (retVal.Length > 0)
						{
							// The caller will strip '+' if !siteConfig.EnablereplacedlePermaLinkSpaces
							retVal.Append("+");
						}

						pendingSpace = false;
					}

					retVal.Append(c);
				}
			}

			return WebUtility.UrlEncode(retVal.ToString()).Replace("%2b", "+", StringComparison.OrdinalIgnoreCase);
		}

19 View Source File : AkismetClient.cs
License : MIT License
Project Creator : poppastring

string SubmitComment(IComment comment, Uri url)
		{
			//Not too many concatenations.  Might not need a string builder.
			string parameters = "blog=" + WebUtility.UrlEncode(this.blogUrl.ToString())
								+ "&user_ip=" + comment.IpAddress.ToString()
								+ "&user_agent=" + WebUtility.UrlEncode(comment.UserAgent);

			if (!String.IsNullOrEmpty(comment.Referer))
				parameters += "&referer=" + WebUtility.UrlEncode(comment.Referer);

			if (comment.Permalink != null)
				parameters += "&permalink=" + WebUtility.UrlEncode(comment.Permalink.ToString());

			if (!String.IsNullOrEmpty(comment.CommentType))
				parameters += "&comment_type=" + WebUtility.UrlEncode(comment.CommentType);

			if (!String.IsNullOrEmpty(comment.Author))
				parameters += "&comment_author=" + WebUtility.UrlEncode(comment.Author);

			if (!String.IsNullOrEmpty(comment.Autreplacedmail))
				parameters += "&comment_author_email=" + WebUtility.UrlEncode(comment.Autreplacedmail);

			if (comment.AuthorUrl != null)
				parameters += "&comment_author_url=" + WebUtility.UrlEncode(comment.AuthorUrl.ToString());

			if (!String.IsNullOrEmpty(comment.Content))
				parameters += "&comment_content=" + WebUtility.UrlEncode(comment.Content);

			if (comment.ServerEnvironmentVariables != null)
			{
				foreach (string key in comment.ServerEnvironmentVariables)
				{
					parameters += "&" + key + "=" + WebUtility.UrlEncode(comment.ServerEnvironmentVariables[key]);
				}
			}

			return this.httpClient.PostRequest(url, this.UserAgent, this.Timeout, parameters).ToLower(CultureInfo.InvariantCulture);
		}

19 View Source File : AkismetClient.cs
License : MIT License
Project Creator : poppastring

public bool VerifyApiKey()
		{
			string parameters = "key=" + WebUtility.UrlEncode(this.ApiKey) + "&blog=" + WebUtility.UrlEncode(this.BlogUrl.ToString());
			string result = this.httpClient.PostRequest(verifyUrl, this.UserAgent, this.Timeout, parameters);

			if (String.IsNullOrEmpty(result))
				throw new InvalidResponseException("Akismet returned an empty response");
			
			return (System.String.Compare("valid", result, true) == 0);
		}

19 View Source File : AkismetClient.cs
License : MIT License
Project Creator : poppastring

string SubmitComment(IComment comment, Uri url)
		{
			//Not too many concatenations.  Might not need a string builder.
			string parameters = "blog=" + WebUtility.UrlEncode(this.blogUrl.ToString())
								+ "&user_ip=" + comment.IpAddress.ToString()
								+ "&user_agent=" + WebUtility.UrlEncode(comment.UserAgent);

			if (!String.IsNullOrEmpty(comment.Referer))
				parameters += "&referer=" + WebUtility.UrlEncode(comment.Referer);

			if (comment.Permalink != null)
				parameters += "&permalink=" + WebUtility.UrlEncode(comment.Permalink.ToString());

			if (!String.IsNullOrEmpty(comment.CommentType))
				parameters += "&comment_type=" + WebUtility.UrlEncode(comment.CommentType);

			if (!String.IsNullOrEmpty(comment.Author))
				parameters += "&comment_author=" + WebUtility.UrlEncode(comment.Author);

			if (!String.IsNullOrEmpty(comment.Autreplacedmail))
				parameters += "&comment_author_email=" + WebUtility.UrlEncode(comment.Autreplacedmail);

			if (comment.AuthorUrl != null)
				parameters += "&comment_author_url=" + WebUtility.UrlEncode(comment.AuthorUrl.ToString());

			if (!String.IsNullOrEmpty(comment.Content))
				parameters += "&comment_content=" + WebUtility.UrlEncode(comment.Content);

			if (comment.ServerEnvironmentVariables != null)
			{
				foreach (string key in comment.ServerEnvironmentVariables)
				{
					parameters += "&" + key + "=" + WebUtility.UrlEncode(comment.ServerEnvironmentVariables[key]);
				}
			}

			return this.httpClient.PostRequest(url, this.UserAgent, this.Timeout, parameters).ToLower(CultureInfo.InvariantCulture);
		}

19 View Source File : Pixeez.cs
License : MIT License
Project Creator : project-violet

public async Task<AsyncResponse> SendRequestAsync(MethodType type, string url, IDictionary<string, string> param, IDictionary<string, string> headers = null)
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Referer", "http://spapi.pixiv.net/");
            httpClient.DefaultRequestHeaders.Add("User-Agent", "PixivIOSApp/5.8.0");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + this.AccessToken);

            if (headers != null)
            {
                foreach (var header in headers)
                    httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
            }

            AsyncResponse asyncResponse = null;

            if (type == MethodType.POST)
            {
                var reqParam = new FormUrlEncodedContent(param);
                var response = await httpClient.PostAsync(url, reqParam);
                asyncResponse = new AsyncResponse(response);
            }
            else if (type == MethodType.DELETE)
            {
                var uri = url;

                if (param != null)
                {
                    var query_string = "";
                    foreach (KeyValuePair<string, string> kvp in param)
                    {
                        if (query_string == "")
                            query_string += "?";
                        else
                            query_string += "&";

                        query_string += kvp.Key + "=" + WebUtility.UrlEncode(kvp.Value);
                    }
                    uri += query_string;
                }
                
                var response = await httpClient.DeleteAsync(uri);
                asyncResponse = new AsyncResponse(response);
            }
            else
            {
                var uri = url;

                if (param != null)
                {
                    var query_string = "";
                    foreach (KeyValuePair<string, string> kvp in param)
                    {
                        if (query_string == "")
                            query_string += "?";
                        else
                            query_string += "&";

                        query_string += kvp.Key + "=" + WebUtility.UrlEncode(kvp.Value);
                    }
                    uri += query_string;
                }

                var response = await httpClient.GetAsync(uri);
                asyncResponse = new AsyncResponse(response);
            }

            return asyncResponse;
        }

19 View Source File : DownloadMappingService.cs
License : GNU General Public License v3.0
Project Creator : Prowlarr

public Uri ConvertToProxyLink(Uri link, string serverUrl, int indexerId, string file = "t")
        {
            var urlBase = _configFileProvider.UrlBase;

            if (urlBase.IsNotNullOrWhiteSpace() && !urlBase.StartsWith("/"))
            {
                urlBase = "/" + urlBase;
            }

            var encryptedLink = _protectionService.Protect(link.ToString());
            var encodedLink = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(encryptedLink));
            var urlEncodedFile = WebUtility.UrlEncode(file);
            var proxyLink = $"{serverUrl}{urlBase}/{indexerId}/download?apikey={_configFileProvider.ApiKey}&link={encodedLink}&file={urlEncodedFile}";
            return new Uri(proxyLink);
        }

19 View Source File : BakaBT.cs
License : GNU General Public License v3.0
Project Creator : Prowlarr

private IEnumerable<IndexerRequest> GetPagedRequests(string term)
        {
            var searchString = term;
            var searchUrl = Settings.BaseUrl + "browse.php?only=0&incomplete=1&lossless=1&hd=1&multiaudio=1&bonus=1&reorder=1&q=";
            if (Settings.AdultContent)
            {
                searchUrl = Settings.BaseUrl + "browse.php?only=0&hentai=1&incomplete=1&lossless=1&hd=1&multiaudio=1&bonus=1&reorder=1&q=";
            }

            var match = Regex.Match(term, @".*(?=\s(?:[Ee]\d+|\d+)$)");
            if (match.Success)
            {
                searchString = match.Value;
            }

            var episodeSearchUrl = searchUrl + WebUtility.UrlEncode(searchString);

            var request = new IndexerRequest(episodeSearchUrl, null);

            yield return request;
        }

See More Examples