当前位置: 首页>>代码示例>>C#>>正文


C# System.UriBuilder类代码示例

本文整理汇总了C#中System.UriBuilder的典型用法代码示例。如果您正苦于以下问题:C# UriBuilder类的具体用法?C# UriBuilder怎么用?C# UriBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


UriBuilder类属于System命名空间,在下文中一共展示了UriBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpRequestMessage request = actionContext.Request;
            string query = request.RequestUri.Query.Substring(1);
            var parts = query.Split('&').ToList();
            bool foundExpand = false;
            for (int i = 0; i < parts.Count; i++)
            {
                string segment = parts[i];
                if (segment.StartsWith(ODataExpandOption, StringComparison.Ordinal))
                {
                    foundExpand = true;
                    parts[i] += "," + this.AlwaysExpand;
                    break;
                }
            }

            if (!foundExpand)
            {
                parts.Add(ODataExpandOption + this.AlwaysExpand);
            }

            UriBuilder modifiedRequestUri = new UriBuilder(request.RequestUri);
            modifiedRequestUri.Query = string.Join("&",
                                        parts.Where(p => p.Length > 0));
            request.RequestUri = modifiedRequestUri.Uri;
            base.OnActionExecuting(actionContext);
        }
开发者ID:shawnhellinckx,项目名称:TravelListTeamStupid,代码行数:28,代码来源:QueryableExpandAttribute.cs

示例2: StressService

        public StressService(Uri serviceBusUri, string username, string password, ushort heartbeat, int iterations, int instances, int messageSize, bool cleanUp, bool mixed, int prefetchCount, int consumerLimit, int requestsPerInstance)
        {
            _username = username;
            _password = password;
            _heartbeat = heartbeat;
            _iterations = iterations;
            _instances = instances;
            _messageSize = messageSize;
            _prefetchCount = prefetchCount;
            _consumerLimit = consumerLimit;
            _requestsPerInstance = requestsPerInstance;
            _cleanUp = cleanUp;
            _mixed = mixed;
            _serviceBusUri = serviceBusUri;
            _messageContent = new string('*', messageSize);

            _clientUri = _serviceBusUri;

            var prefetch = new Regex(@"([\?\&])prefetch=[^\&]+[\&]?");
            string query = _serviceBusUri.Query;

            if (query.IndexOf("prefetch", StringComparison.InvariantCultureIgnoreCase) >= 0)
                query = prefetch.Replace(query, string.Format("prefetch={0}", _prefetchCount));
            else if (string.IsNullOrEmpty(query))
                query = string.Format("prefetch={0}", _prefetchCount);
            else
                query += string.Format("&prefetch={0}", _prefetchCount);

            var builder = new UriBuilder(_serviceBusUri);
            builder.Query = query.Trim('?');
            _serviceBusUri = builder.Uri;

            _cancel = new CancellationTokenSource();
            _clientTasks = new List<Task>();
        }
开发者ID:sadprofessor,项目名称:MassTransit-Stress,代码行数:35,代码来源:StressService.cs

示例3: FindExecutionDirectory

 public static string FindExecutionDirectory(Assembly assembly)
 {
     string applicationPath = assembly.CodeBase;
     UriBuilder uri = new UriBuilder(applicationPath);
     string path = Uri.UnescapeDataString(uri.Path);
     return Path.GetDirectoryName(path);
 }
开发者ID:gwicksted,项目名称:Findall,代码行数:7,代码来源:ExecutionDirectory.cs

示例4: ExternalSearchService

        public ExternalSearchService(IAppConfiguration config, IDiagnosticsService diagnostics)
        {
            ServiceUri = config.ServiceDiscoveryUri;

            Trace = diagnostics.SafeGetSource("ExternalSearchService");

            // Extract credentials
            var userInfo = ServiceUri.UserInfo;
            ICredentials credentials = null;
            if (!String.IsNullOrEmpty(userInfo))
            {
                var split = userInfo.Split(':');
                if (split.Length != 2)
                {
                    throw new FormatException("Invalid user info in SearchServiceUri!");
                }

                // Split the credentials out
                credentials = new NetworkCredential(split[0], split[1]);
                ServiceUri = new UriBuilder(ServiceUri)
                {
                    UserName = null,
                    Password = null
                }.Uri;
            }

            if (_healthIndicatorStore == null)
            {
                _healthIndicatorStore = new BaseUrlHealthIndicatorStore(new AppInsightsHealthIndicatorLogger());
            }

            _client = new SearchClient(ServiceUri, config.SearchServiceResourceType, credentials, _healthIndicatorStore, new TracingHttpHandler(Trace));
        }
开发者ID:ashuthinks,项目名称:webnuget,代码行数:33,代码来源:ExternalSearchService.cs

示例5: GeocodeAsync

        private async Task<Response> GeocodeAsync(IDictionary<string, string> query)
        {
            // build the request URI
            var builder = new UriBuilder(_endpoint);
            var resultingQuery = new Dictionary<string, string>();
            foreach (string key in query.Keys)
            {
                resultingQuery[key] = query[key];
            }
            resultingQuery["format"] = "jsonv2";
            resultingQuery["polygon"] = "1";
            resultingQuery["addressdetails"] = "1";
            var requestUri = QueryHelpers.AddQueryString(_endpoint, resultingQuery);

            // get the response
            ClientResponse clientResponse = await _client.GetAsync(requestUri).ConfigureAwait(false);

            // parse the response
            string content = Encoding.UTF8.GetString(clientResponse.Content);
            var places = JsonConvert.DeserializeObject<Place[]>(content);

            // project the response
            return new Response
            {
                Locations = places.Select(p => new Location
                {
                    Name = p.DisplayName,
                    Latitude = p.Latitude,
                    Longitude = p.Longitude
                }).ToArray()
            };
        }
开发者ID:joelverhagen,项目名称:PolyGeocoder,代码行数:32,代码来源:OpenStreetMapGeocoder.cs

示例6: GetPluginDirectory

 public static string GetPluginDirectory()
 {
     string codeBase = Assembly.GetExecutingAssembly().CodeBase;
     UriBuilder uri = new UriBuilder(codeBase);
     string path = Uri.UnescapeDataString(uri.Path);
     return Path.GetDirectoryName(path);
 }
开发者ID:emir01,项目名称:spike.mef.plugins,代码行数:7,代码来源:ConfigurationUtilities.cs

示例7: ApiCall

        private string ApiCall(string action, NameValueCollection queries = null)
        {
            string result = string.Empty;

            try {

                // if null, create new one, even it's empty
                if (queries == null)
                    queries = new NameValueCollection();

                // always attach access_token
                queries.Add("access_token", this.AccessToken);

                var requestUrl = new UriBuilder();
                requestUrl.Scheme = "https";
                requestUrl.Host = "api.instagram.com";
                requestUrl.Path = action;
                requestUrl.Query = string.Join("&", queries.AllKeys.Select(c => string.Format("{0}={1}", HttpUtility.UrlEncode(c), HttpUtility.UrlEncode(queries[c]))));

                var req = (HttpWebRequest)WebRequest.Create(requestUrl.ToString());
                var res = (HttpWebResponse)req.GetResponse();

                using (StreamReader stream = new StreamReader(res.GetResponseStream())) {
                    result = stream.ReadToEnd();
                    stream.Close();
                }
            } catch (Exception ex) {
                if (ex.Message.Contains("400")) {
                    // invalid response
                    result = ex.Message;
                }
            }

            return result;
        }
开发者ID:nonintanon,项目名称:zupzip9,代码行数:35,代码来源:InstagramController.cs

示例8: GetDomain

        public static void GetDomain(string fromUrl, out string domain, out string subDomain)
        {
            domain = "";
            subDomain = "";
            try
            {
                if (fromUrl.IndexOf("的名片") > -1)
                {
                    subDomain = fromUrl;
                    domain = "名片";
                    return;
                }

                UriBuilder builder = new UriBuilder(fromUrl);
                fromUrl = builder.ToString();

                Uri u = new Uri(fromUrl);

                if (u.IsWellFormedOriginalString())
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";

                    }
                    else
                    {
                        string Authority = u.Authority;
                        string[] ss = u.Authority.Split('.');
                        if (ss.Length == 2)
                        {
                            Authority = "www." + Authority;
                        }
                        int index = Authority.IndexOf('.', 0);
                        domain = Authority.Substring(index + 1, Authority.Length - index - 1).Replace("comhttp","com");
                        subDomain = Authority.Replace("comhttp", "com");
                        if (ss.Length < 2)
                        {
                            domain = "不明路径";
                            subDomain = "不明路径";
                        }
                    }
                }
                else
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";
                    }
                    else
                    {
                        subDomain = domain = "不明路径";
                    }
                }
            }
            catch
            {
                subDomain = domain = "不明路径";
            }
        }
开发者ID:Rainyhhh,项目名称:International-Website,代码行数:60,代码来源:UrlOper.cs

示例9: RpcToWcf

        public static string RpcToWcf(EndpointBindingInfo bindingInfo)
        {
            if (bindingInfo.Protseq == RpcProtseq.ncacn_ip_tcp)
            {
                return new UriBuilder(Uri.UriSchemeNetTcp, bindingInfo.NetworkAddr, Int32.Parse(bindingInfo.EndPoint)).Uri.ToString();
            }
            if (bindingInfo.Protseq == RpcProtseq.ncalrpc)
            {

                var path = bindingInfo.EndPoint;

                var builder = new UriBuilder(UriSchemeIpc,null);
                builder.Path = path;
                //TODO: use builder to build with empty host ///
                //builder.Host = string.Empty;
                //return builder.Uri.ToString();
                string local = ":///";
                return builder.Scheme + local + builder.Path;
            }
            if (bindingInfo.Protseq == RpcProtseq.ncacn_np)
            {
                var path = bindingInfo.EndPoint.Replace(@"\pipe", string.Empty).Replace("\\", "/");
                var builder = new UriBuilder(Uri.UriSchemeNetPipe, bindingInfo.NetworkAddr);
                builder.Path = path;
                return builder.Uri.ToString();
            }
            throw new NotImplementedException(bindingInfo.Protseq + " not implemented");
        }
开发者ID:OpenSharp,项目名称:NDceRpc,代码行数:28,代码来源:EndpointMapper.cs

示例10: Combine

 /// <summary>
 /// Combines the specified OPC DA server URL with path.
 /// </summary>
 /// <param name="url">The OPC DA server URL.</param>
 /// <param name="path">The path.</param>
 /// <returns>
 /// The OPC DA server URL with path.
 /// </returns>
 public static Uri Combine(Uri url, string path)
 {
     var uriBuilder = new UriBuilder(url);
     uriBuilder.Path = string.Concat(uriBuilder.Path, @"/", Uri.EscapeDataString(path)); //workaround for split ProgId & ItemId in URL path
     Uri result = uriBuilder.Uri;
     return result;
 }
开发者ID:yuriik83,项目名称:TitaniumAS.Opc.Client,代码行数:15,代码来源:UrlBuilder.cs

示例11: InvokeDeleteContent

        public static bool InvokeDeleteContent(int id)
        {
            try
            {
                UriBuilder getQuestionsUri = new UriBuilder(Properties.Settings.Default.CloudCommunityUrlNew + @"/Resource/Service/Content/" + id.ToString());
                string appSecurityToken = Properties.Settings.Default.LiveIdToken;
                string body;
                WebRequest request = WebRequest.Create(getQuestionsUri.Uri);
                request.Method = "Delete";
                request.ContentLength = 0;
                request.Headers.Add(@"LiveUserToken", appSecurityToken);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseStreamReader = new StreamReader(responseStream))
                        {
                            body = responseStreamReader.ReadToEnd();
                            body = body.Substring(body.IndexOf('>') + 1);
                            body = body.Substring(0, body.IndexOf('<'));
                            return Boolean.Parse(body);
                        }
                    }
                }
            }
            catch
            {

            }
            return false;
        }
开发者ID:ngonzalezromero,项目名称:wwt-windows-client,代码行数:32,代码来源:EOCalls.cs

示例12: Search

    public void Search(string searchtag)
    {
      if (searchtag == null) return;
      if (searchtag == string.Empty) return;
      m_imageList.DisposeAndClearList();
      try
      {
        UriBuilder builder = new UriBuilder();
        builder.Host = "images.google.nl";
        builder.Path = "/images";
        builder.Query = String.Format("q={0}", searchtag);

        // Make the Webrequest
        WebRequest req = WebRequest.Create(builder.Uri.AbsoluteUri);
        try
        {
          // Use the current user in case an NTLM Proxy or similar is used.
          // wr.Proxy = WebProxy.GetDefaultProxy();
          req.Proxy.Credentials = CredentialCache.DefaultCredentials;
        }
        catch (Exception) {}
        WebResponse result = req.GetResponse();
        using (Stream ReceiveStream = result.GetResponseStream())
        {
          StreamReader sr = new StreamReader(ReceiveStream);
          string strBody = sr.ReadToEnd();
          Parse(strBody);
        }
      }
      catch (Exception ex)
      {
        Log.Warn("get failed:{0}", ex.Message);
      }
    }
开发者ID:arangas,项目名称:MediaPortal-1,代码行数:34,代码来源:GoogleImageSearch.cs

示例13: ProcessRequest

 public void ProcessRequest(HttpContext context)
 {
     if (context == null)
     {
         throw new HttpException("HttpContext was unavailable.");
     }
     TheKnot.Membership.Security.Authentication.Provider.DeleteMsdTicket();
     UriBuilder builder = new UriBuilder(context.Request.QueryString["originalTarget"]);
     if ((builder == null) || (builder.Uri.PathAndQuery.Trim().Length == 0))
     {
         throw new TheKnot.Membership.Security.Providers.CustomAuthenticationException("The application requires 'originalTarget' as query string variable.");
     }
     if (builder.Query.IndexOf("MsdVisit") == -1)
     {
         if (builder.Query.Length > 0)
         {
             builder.Query = builder.Query + "&MsdVisit=1";
         }
         else
         {
             builder.Query = "MsdVisit=1";
         }
     }
     context.Response.Redirect(builder.Uri.AbsoluteUri, true);
 }
开发者ID:haizhixing126,项目名称:PYSConsole,代码行数:25,代码来源:MsdTicketDeletionHandler.cs

示例14: OnAuthorization

        /// <summary>
        /// The OnAuthorization method checks if the request is in HTTPS format or not and passed the Authorization task to the base class.
        /// </summary>
        /// <param name="actionContext">Context of the request.</param>        
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var request = actionContext.Request;

            // Check if the request uri scheme is in HTTPS format.
            if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                var response = new HttpResponseMessage();

                if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Head)
                {
                    var uri = new UriBuilder(request.RequestUri);
                    uri.Scheme = Uri.UriSchemeHttps;
                    uri.Port = this.Port;

                    response.StatusCode = HttpStatusCode.Found;
                    response.Headers.Location = uri.Uri;
                }
                else
                {
                    response.StatusCode = HttpStatusCode.Forbidden;
                }

                actionContext.Response = response;
            }
            else
            {
                // Call the OnAuthorization method of the base class.
                base.OnAuthorization(actionContext);
            }
        }
开发者ID:gauravmokhasi,项目名称:EventFrameworkPOC,代码行数:35,代码来源:RequireHttpsAttribute.cs

示例15: Solve

        /// <summary>
        /// Determines a route between two or more points.
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <exception cref="SolveException"></exception>
        public SolveResult Solve(SolveParameters parameters, Token token)
        {
            UriBuilder uriBuilder = new UriBuilder(this.Uri);
            uriBuilder.Path += "solve";
            string qs = parameters.ToQueryString();
            if (token != null)
            {
                qs = string.Format("token={1}&{0}&f=json", qs, token.AccessToken);
            }
            uriBuilder.Query = qs;

            var request = HttpWebRequest.Create(uriBuilder.Uri) as HttpWebRequest;
            string json = null;
            using (var response = request.GetResponse() as HttpWebResponse)
            {
                var stream = response.GetResponseStream();
                using (var streamReader = new StreamReader(stream))
                {
                    json = streamReader.ReadToEnd();
                }
            }

            // If the request returned an error, throw an exception.
            var errorResponse = JsonConvert.DeserializeObject<SolveErrorResponse>(json);
            if (errorResponse.error != null)
            {
                throw new SolveException(errorResponse);
            }

            SolveResult solveResult = null;

            solveResult = JsonConvert.DeserializeObject<SolveResult>(json);

            return solveResult;
        }
开发者ID:WSDOT-GIS,项目名称:ArcGisServerRestApiWrapper,代码行数:42,代码来源:RouteService.cs


注:本文中的System.UriBuilder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。