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


C# Uri类代码示例

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


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

示例1: ConnectAsync_AddCustomHeaders_Success

        public async Task ConnectAsync_AddCustomHeaders_Success(Uri server)
        {
            using (var cws = new ClientWebSocket())
            {
                cws.Options.SetRequestHeader("X-CustomHeader1", "Value1");
                cws.Options.SetRequestHeader("X-CustomHeader2", "Value2");
                using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
                {
                    Task taskConnect = cws.ConnectAsync(server, cts.Token);
                    Assert.True(
                        (cws.State == WebSocketState.None) ||
                        (cws.State == WebSocketState.Connecting) ||
                        (cws.State == WebSocketState.Open),
                        "State immediately after ConnectAsync incorrect: " + cws.State);
                    await taskConnect;
                }

                Assert.Equal(WebSocketState.Open, cws.State);

                byte[] buffer = new byte[65536];
                var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
                WebSocketReceiveResult recvResult;
                using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
                {
                    recvResult = await cws.ReceiveAsync(segment, cts.Token);
                }

                Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
                string headers = WebSocketData.GetTextFromBuffer(segment);
                Assert.True(headers.Contains("X-CustomHeader1:Value1"));
                Assert.True(headers.Contains("X-CustomHeader2:Value2"));

                await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:35,代码来源:ClientWebSocketTest.cs

示例2: Add

    // properties

    // methods

        /// <devdoc>
        /// <para>Adds a <see cref='System.Net.NetworkCredential'/>
        /// instance to the credential cache.</para>
        /// </devdoc>
        // UEUE
        public void Add(Uri uriPrefix, string authType, NetworkCredential cred) {
            //
            // parameter validation
            //
            if (uriPrefix==null) {
                throw new ArgumentNullException("uriPrefix");
            }
            if (authType==null) {
                throw new ArgumentNullException("authType");
            }
            if ((cred is SystemNetworkCredential)
#if !FEATURE_PAL
                && !((string.Compare(authType, NtlmClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (DigestClient.WDigestAvailable && (string.Compare(authType, DigestClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
                     || (string.Compare(authType, KerberosClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (string.Compare(authType, NegotiateClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
#endif
                ) {
                throw new ArgumentException(SR.GetString(SR.net_nodefaultcreds, authType), "authType");
            }

            ++m_version;

            CredentialKey key = new CredentialKey(uriPrefix, authType);

            GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + cred.Domain + "],[" + cred.UserName + "]");

            cache.Add(key, cred);
            if (cred is SystemNetworkCredential) {
                ++m_NumbDefaultCredInCache;
            }
        }
开发者ID:yangjunhua,项目名称:mono,代码行数:41,代码来源:CredentialCache.cs

示例3: Launch_Click

 private async void Launch_Click(object sender, RoutedEventArgs e)
 {
     if (FacebookClientID.Text == "")
     {
         rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
         return;
     }
  
     var uri = new Uri("https://graph.facebook.com/me");
     HttpClient httpClient = GetAutoPickerHttpClient(FacebookClientID.Text);
     
     DebugPrint("Getting data from facebook....");
     var request = new HttpRequestMessage(HttpMethod.Get, uri);
     try
     {
         var response = await httpClient.SendRequestAsync(request);
         if (response.IsSuccessStatusCode)
         {
             string userInfo = await response.Content.ReadAsStringAsync();
             DebugPrint(userInfo);
         }
         else
         {
             string str = "";
             if (response.Content != null) 
                 str = await response.Content.ReadAsStringAsync();
             DebugPrint("ERROR: " + response.StatusCode + " " + response.ReasonPhrase + "\r\n" + str);
         }
     }
     catch (Exception ex)
     {
         DebugPrint("EXCEPTION: " + ex.Message);
     }
 }
开发者ID:mbin,项目名称:Win81App,代码行数:34,代码来源:Scenario6.xaml.cs

示例4: UriToString

        internal static string UriToString(Uri uri)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(uri != null, "uri != null");

            return uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString;
        }
开发者ID:rambo-returns,项目名称:MonoRail,代码行数:7,代码来源:UriUtils.cs

示例5: ProxyExplicitlyProvided_DefaultCredentials_Ignored

        public void ProxyExplicitlyProvided_DefaultCredentials_Ignored()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            var rightCreds = new NetworkCredential("rightusername", "rightpassword");
            var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword");

            using (var handler = new HttpClientHandler())
            using (var client = new HttpClient(handler))
            {
                handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds);
                handler.DefaultProxyCredentials = wrongCreds;

                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
开发者ID:naamunds,项目名称:corefx,代码行数:26,代码来源:HttpClientHandlerTest.DefaultProxyCredentials.cs

示例6: GetEntity

        // Maps a URI to an Object containing the actual resource.
        public override Object GetEntity(Uri uri, string role, Type typeOfObjectToReturn)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (typeOfObjectToReturn != null && typeOfObjectToReturn != typeof(Stream) && typeOfObjectToReturn != typeof(Object))
            {
                throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
            }

            string filePath = uri.OriginalString;
            if (uri.IsAbsoluteUri)
            {
                if (!uri.IsFile)
                    throw new XmlException(SR.Format(SR.Xml_SystemPathResolverCannotOpenUri, uri.ToString()));

                filePath = uri.LocalPath;
            }

            try
            {
                return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (ArgumentException e)
            {
                throw new XmlException(SR.Format(SR.Xml_SystemPathResolverCannotOpenUri, uri.ToString()), e);
            }
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:31,代码来源:XmlSystemPathResolver.cs

示例7: ProcessDocument

    void ProcessDocument(Uri url)
    {
        Console.Error.WriteLine ("Processing {0}...", url);

        var doc = FetchXmlDocument (url);

        var baseTable = doc.SelectSingleNode ("//table[@class='jd-inheritance-table']");
        var baseTypeName = baseTable.SelectSingleNode ("tr[last() - 1]/td[last()]").InnerText;

        fs1.WriteLine ("<class name='{0}' url='{1}' base='{2}'>", GetName (url), url, baseTypeName);
        /*
        var table = doc.SelectSingleNode ("//table[@id='lattrs']");
        if (table != null) {
            var nodes = table.SelectNodes ("tr[contains(@class,'api')]");
            foreach (XmlNode node in nodes) {
                var attr = node.SelectSingleNode ("td[1]//text()");
                var method = node.SelectSingleNode ("td[2]//text()");
                var a = attr.InnerText;
                fs1.WriteLine ("<a>{0}</a>", a);//node.SelectSingleNode ("td[1]"));
                if (!atts.Contains (a))
                    atts.Add (a);
            }
        }
        */
        fs1.WriteLine ("</class>");
        fs1.Flush ();
    }
开发者ID:atsushieno,项目名称:monodroid-schema-gen,代码行数:27,代码来源:type-hierarchy-importer.cs

示例8: GetAuthorizationUrl

    /// <summary>
    /// Retrieve the URL that the client should redirect the user to to perform the OAuth authorization
    /// </summary>
    /// <param name="provider"></param>
    /// <returns></returns>
    protected override string GetAuthorizationUrl(String callbackUrl)
    {
        OAuthBase auth = new OAuthBase();
        String requestUrl = provider.Host + provider.RequestTokenUrl;
        Uri url = new Uri(requestUrl);
        String requestParams = "";
        String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, null, null, provider.RequestTokenMethod ?? "POST",
            auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams,
            new OAuthBase.QueryParameter(OAuthBase.OAuthCallbackKey, auth.UrlEncode(callbackUrl)));
        requestParams += "&oauth_signature=" + HttpUtility.UrlEncode(signature);
        WebClient webClient = new WebClient();
        byte[] response;
        if (provider.RequestTokenMethod == "POST" || provider.RequestTokenMethod == null)
        {
            response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams));
        }
        else
        {
            response = webClient.DownloadData(url + "?" + requestParams);
        }
        Match m = Regex.Match(Encoding.ASCII.GetString(response), "oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=true");
        String requestToken = m.Groups[1].Value;
        String requestTokenSecret = m.Groups[2].Value;
        // we need a way to save the request token & secret, so that we can use it to get the access token later (when they enter the pin)
        // just stick it in the session for now
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SESSIONKEY] = requestToken;
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SECRET_SESSIONKEY] = requestTokenSecret;

        return provider.Host + provider.UserApprovalUrl + "?oauth_token=" + HttpUtility.UrlEncode(requestToken);
    }
开发者ID:ssommerfeldt,项目名称:TAC_EAB,代码行数:35,代码来源:OAuth1AuthorizationServiceViewController.cs

示例9: VolumeSource

		public VolumeSource (Gnome.Vfs.Volume vol)
		{
			this.Volume = vol;
			this.Name = vol.DisplayName;

			try {
				mount_point = new Uri (vol.ActivationUri).LocalPath;
			} catch (System.Exception e) {
				System.Console.WriteLine (e);
			}

			uri = mount_point;
			
                        if (this.Icon == null)
				this.Icon = PixbufUtils.LoadThemeIcon (vol.Icon, 32);
			
			if (this.IsIPodPhoto)
				this.Icon = PixbufUtils.LoadThemeIcon ("gnome-dev-ipod", 32);

			if (this.Icon == null && this.IsCamera)
				this.Icon = PixbufUtils.LoadThemeIcon ("gnome-dev-media-cf", 32);

			try {
				if (this.Icon == null)
					this.Icon = new Gdk.Pixbuf (vol.Icon);
			} catch (System.Exception e) {
				System.Console.WriteLine (e.ToString ());
			}
		}
开发者ID:AminBonyadUni,项目名称:facedetect-f-spot,代码行数:29,代码来源:ImportCommand.cs

示例10: NavigationProgressEventArgs

 // Internal constructor
 // <param name="uri">URI of the markup page to navigate to.</param>
 // <param name="bytesRead">The number of bytes that have already been downloaded.</param>
 // <param name="maxBytes">The maximum number of bytes to be downloaded.</param>
 // <param name="Navigator">navigator that raised this event</param>
 internal NavigationProgressEventArgs(Uri uri, long bytesRead, long maxBytes, object Navigator)
 {
     _uri = uri;
     _bytesRead = bytesRead;
     _maxBytes = maxBytes;
     _navigator = Navigator;
 }
开发者ID:JianwenSun,项目名称:cc,代码行数:12,代码来源:NavigationProgressEventArgs.cs

示例11: MainPage

        public MainPage()
        {
            this.InitializeComponent();

            //
            // Every Windows Store application has a unique URI.
            // Windows ensures that only this application will receive messages sent to this URI.
            // ADAL uses this URI as the application's redirect URI to receive OAuth responses.
            // 
            // To determine this application's redirect URI, which is necessary when registering the app
            //      in AAD, set a breakpoint on the next line, run the app, and copy the string value of the URI.
            //      This is the only purposes of this line of code, it has no functional purpose in the application.
            //
            redirectURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

            authContext = new AuthenticationContext(authority);

            //
            // Out of the box, this sample is *not* configured to work with Windows Integrated Authentication (WIA)
            // when used with a federated Azure Active Directory domain.  To work with WIA the application manifest
            // must enable additional capabilities.  These are not configured by default for this sample because 
            // applications requesting the Enterprise Authentication or Shared User Certificates capabilities require 
            // a higher level of verification to be accepted into the Windows Store, and not all developers may wish
            // to perform the higher level of verification.
            //
            // To enable Windows Integrated Authentication, in Package.appxmanifest, in the Capabilities tab, enable:
            // * Enterprise Authentication
            // * Private Networks (Client & Server)
            // * Shared User Certificates
            //
            // Plus uncomment the following line of code:
            // 
            // authContext.UseCorporateNetwork = true;

        }
开发者ID:michaellperry,项目名称:NativeClient-WindowsStore,代码行数:35,代码来源:MainPage.xaml.cs

示例12: AsyncPresence

        /// <summary>
        /// Get Presence information per user.
        /// </summary>
        private async void AsyncPresence()
        {
            var client = new HttpClient();

            var uri = new Uri(string.Format(Configurations.PresenceUrl, Configurations.ApiKey, _currentMember.id));
            var response = await client.GetAsync(uri);
            var statusCode = response.StatusCode;
            switch (statusCode)
            {
                // TODO: Error handling for invalid htpp responses.
            }
            response.EnsureSuccessStatusCode();
            var theResponse = await response.Content.ReadAsStringAsync();
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(theResponse)))
            {
                var serializer = new DataContractJsonSerializer(typeof(PresenceRoot));
                var presenceObject = serializer.ReadObject(ms) as PresenceRoot;
                // This will allow the application to toggle the presence indicator color.    
                if (presenceObject != null && presenceObject.ok && presenceObject.IsActive())
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        StatusIndicator.Fill = new SolidColorBrush(Color.FromArgb(255, 127, 153, 71));
                    });
                }
                // TODO: Add more code for bad replies or invalid requests.
            }
        }
开发者ID:firebellys,项目名称:slack-list,代码行数:31,代码来源:ProfilePage.xaml.cs

示例13: GenerateHttpWebRequest

    public static HttpWebRequest GenerateHttpWebRequest(Uri uri)
    {
        //all this mess below is my attempt to resolve some of the issues in taking on various conflicts in httpreqeust.
            //code is left in
            //if infact requests vary may need to switch(key) on differnet sites?

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.672.2 Safari/534.2";

            CookieContainer cc = new CookieContainer();
            httpRequest.CookieContainer = cc;//must assing a cookie container for the request to pull the cookies

            httpRequest.AllowAutoRedirect = true;   //example, Hanes.com

            httpRequest.Credentials = CredentialCache.DefaultCredentials;

            //httpRequest.Headers.Add("HTTP_USER_AGENT", @"Mozilla/5.0(PC) (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4");

            //   httpRequest.Headers.Add("Agent", "Mozilla/5.0(PC) (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4");
            //   httpRequest.Headers.Add("Accept-Charset", "ISO-8859-1");
            /*

            httpRequest.Headers.Add("Accept-Language", "en-us,en;q=0.5");
            httpRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
            httpRequest.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

          //  httpRequest.Headers.Add("Set-Cookie", response.Headers("Set-Cookie"));
            httpRequest.Headers.Add("Agent", "Mozilla//5.0 (X11; U; Linux i686; en-US; ry; 1.8.0.7) Geck//20060925 Firefox//1.5.0.7");
            */

            return httpRequest;
    }
开发者ID:blat001,项目名称:Achievement-Sherpa,代码行数:33,代码来源:DownloadHelper.cs

示例14: DocumentationIndexIsUpToDate

    public void DocumentationIndexIsUpToDate()
    {
        var documentationIndexFile = ReadDocumentationFile("../mkdocs.yml");
        var docsDirectoryPath = new Uri(docsDirectory.FullName, UriKind.Absolute);

        Console.WriteLine(docsDirectoryPath);

        foreach (var markdownFile in docsDirectory.EnumerateFiles("*.md", SearchOption.AllDirectories))
        {
            var fullPath = new Uri(markdownFile.FullName, UriKind.Absolute);
            var relativePath = docsDirectoryPath
                .MakeRelativeUri(fullPath)
                .ToString()
                .Replace("docs/", string.Empty);

            // The readme file in the docs directory is not supposed to be deployed to ReadTheDocs;
            // it's only there for the convenience of contributors wanting to improve the documentation itself.
            if (relativePath == "readme.md")
            {
                continue;
            }

            documentationIndexFile.ShouldContain(relativePath, () => string.Format("The file '{0}' is not listed in 'mkdocs.yml'.", relativePath));
        }
    }
开发者ID:qetza,项目名称:GitVersion,代码行数:25,代码来源:DocumentationTests.cs

示例15: UriIsWellFormed_NewAbsoluteUnregisteredAsRelative_Throws

 public void UriIsWellFormed_NewAbsoluteUnregisteredAsRelative_Throws()
 {
     Assert.ThrowsAny<FormatException>(() =>
   {
       Uri test = new Uri("any://foo", UriKind.Relative);
   });
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:7,代码来源:UriIsWellFormedUriStringTest.cs


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