本文整理汇总了C#中Uri.GetLeftPart方法的典型用法代码示例。如果您正苦于以下问题:C# Uri.GetLeftPart方法的具体用法?C# Uri.GetLeftPart怎么用?C# Uri.GetLeftPart使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Uri
的用法示例。
在下文中一共展示了Uri.GetLeftPart方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Page_Init
protected void Page_Init(object sender, EventArgs e)
{
if (Request.Params.Count == 0)
Response.Redirect("~/Default.aspx");
string guid = null;
if (Request.Params["oldGUID"] != null && Request.Params["newGUID"] != null)
{
string oldGUID = Request.Params["oldGUID"].ToString();
guid = Request.Params["newGUID"].ToString();
MySession.DuplicateSession(oldGUID, guid);
SESSIONID.Value = guid;
string parametres = MySession.GetParams();
Uri myUri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);
string redirection = "";
if (parametres != null && parametres.Length > 0)
redirection = myUri.GetLeftPart(UriPartial.Path) + MySession.GenerateGetParamsWithNewGUID(parametres, guid);
else
redirection = myUri.GetLeftPart(UriPartial.Path) + MySession.GenerateGetParamsWithNewGUID(guid);
Response.Redirect(redirection);
}
else
{
if (guid == null || guid == string.Empty)
guid = Request.Form["ctl00$SESSIONID"];
if (guid == null || guid == string.Empty)
guid = MySession.GetParam("SESSIONID");
if (guid != null)
SESSIONID.Value = guid;
}
}
示例2: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
rptEntities.DataSource = companyFac.GetAllEntities();
rptEntities.DataBind();
int id = Convert.ToInt32(Request.QueryString["ID"]);
if (id != 0)
{
ShowCompany.Attributes.Remove("hidden");
comp = companyFac.GetEntityByID(id);
PopulateFields();
}
else if (Request.QueryString["NewItem"] == "true")
{
ShowCompany.Attributes.Remove("hidden");
comp = new Company();
}
else if (Convert.ToInt32(Request.QueryString["DID"]) > 0)
{
int deleteID = Convert.ToInt32(Request.QueryString["DID"]);
companyFac.Delete(deleteID);
var uri = new Uri(Request.Url.AbsoluteUri);
string path = uri.GetLeftPart(UriPartial.Path);
Response.Redirect(path);
}
}
示例3: GetFacebookAccessToken
private string GetFacebookAccessToken(string code)
{
string secretCode = "7f985ab276fbafaae72afed868937a06";
string url = "https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}";
string page = Path.GetFileNameWithoutExtension(Request.Url.AbsolutePath).ToLower();
if (page != "default")
{
Uri uri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);
siteUrl = uri.GetLeftPart(UriPartial.Path);
}
url = String.Format(url, FaceBookAppKey, HttpUtility.UrlEncode("http://postaround.me/"), secretCode, code);
string response = Tools.CallUrl(url);
// now we got the string string: 'access_token=gfdgfdgd&expires=5108' or an error message
string accessToken = null;
if (response.Contains("access_token"))
{
//take only the access token part
accessToken = response.Split('&')[0];
//take only the token itself
accessToken = accessToken.Split('=')[1];
}
return accessToken;
}
示例4: DiscoverAny
public DiscoveryDocument DiscoverAny (string url)
{
try
{
string contentType = null;
Stream stream = Download (ref url, ref contentType);
if (contentType.IndexOf ("text/html") != -1)
{
// Look for an alternate url
StreamReader sr = new StreamReader (stream);
string str = sr.ReadToEnd ();
string rex = "link\\s*rel\\s*=\\s*[\"']?alternate[\"']?\\s*";
rex += "type\\s*=\\s*[\"']?text/xml[\"']?\\s*href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^']*)'|(?<1>\\S+))";
Regex rob = new Regex (rex, RegexOptions.IgnoreCase);
Match m = rob.Match (str);
if (!m.Success)
throw new InvalidOperationException ("The HTML document does not contain Web service discovery information");
if (url.StartsWith ("/"))
{
Uri uri = new Uri (url);
url = uri.GetLeftPart (UriPartial.Authority) + m.Groups[1];
}
else
{
int i = url.LastIndexOf ('/');
if (i == -1)
throw new InvalidOperationException ("The HTML document does not contain Web service discovery information");
Uri tmp = new Uri (url);
tmp = new Uri (tmp, m.Groups [1].ToString ());
url = tmp.ToString ();
}
stream = Download (ref url);
}
XmlTextReader reader = new XmlTextReader (url, stream);
reader.XmlResolver = null;
reader.MoveToContent ();
DiscoveryDocument doc;
DiscoveryReference refe = null;
if (DiscoveryDocument.CanRead (reader))
{
doc = DiscoveryDocument.Read (reader);
documents.Add (url, doc);
refe = new DiscoveryDocumentReference ();
AddDiscoReferences (doc);
}
#if !MONOTOUCH
else if (ServiceDescription.CanRead (reader))
{
ServiceDescription wsdl = ServiceDescription.Read (reader);
documents.Add (url, wsdl);
doc = new DiscoveryDocument ();
refe = new ContractReference ();
doc.References.Add (refe);
refe.Url = url;
((ContractReference)refe).ResolveInternal (this, wsdl);
}
#endif
else
{
XmlSchema schema = XmlSchema.Read (reader, null);
documents.Add (url, schema);
doc = new DiscoveryDocument ();
refe = new SchemaReference ();
refe.Url = url;
((SchemaReference)refe).ResolveInternal (this, schema);
doc.References.Add (refe);
}
refe.ClientProtocol = this;
refe.Url = url;
references.Add (url, refe);
reader.Close ();
return doc;
}
catch (DiscoveryException ex) {
throw ex.Exception;
}
}
示例5: ValidateAudienceRestriction
/// <summary>
/// Checks the given list of Audience URIs with the AllowedAudienceUri list.
/// </summary>
/// <param name="allowedAudienceUris">Collection of AudienceUris.</param>
/// <param name="tokenAudiences">Collection of audience URIs the token applies to.</param>
/// <exception cref="ArgumentNullException">The input argument 'allowedAudienceUris' is null.</exception>
/// <exception cref="ArgumentNullException">The input argument 'tokenAudiences' is null.</exception>
/// <exception cref="AudienceUriValidationFailedException">Either the input argument 'tokenAudiences' or the configured
/// 'AudienceUris' collection is empty.</exception>
public virtual void ValidateAudienceRestriction(IList<Uri> allowedAudienceUris, IList<Uri> tokenAudiences)
{
if (null == allowedAudienceUris)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("allowedAudienceUris");
}
if (null == tokenAudiences)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenAudiences");
}
if (0 == tokenAudiences.Count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(
SR.GetString(SR.ID1036)));
}
if (0 == allowedAudienceUris.Count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(
SR.GetString(SR.ID1043)));
}
bool found = false;
foreach (Uri audience in tokenAudiences)
{
if (audience != null)
{
// Strip off any query string or fragment. This is necessary because the
// CardSpace uses the raw Request-URI to form the audience when issuing
// tokens for personal cards, but we clearly don't want things like the
// ReturnUrl parameter affecting the audience matching.
Uri audienceLeftPart;
if (audience.IsAbsoluteUri)
{
audienceLeftPart = new Uri(audience.GetLeftPart(UriPartial.Path));
}
else
{
Uri baseUri = new Uri("http://www.example.com");
Uri resolved = new Uri(baseUri, audience);
audienceLeftPart = baseUri.MakeRelativeUri(new Uri(resolved.GetLeftPart(UriPartial.Path)));
}
if (allowedAudienceUris.Contains(audienceLeftPart))
{
found = true;
break;
}
}
}
if (!found)
{
#pragma warning suppress 56506
if (1 == tokenAudiences.Count || null != tokenAudiences[0])
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(
SR.GetString(SR.ID1038, tokenAudiences[0].OriginalString)));
}
else
{
StringBuilder sb = new StringBuilder(SR.GetString(SR.ID8007));
bool first = true;
foreach (Uri a in tokenAudiences)
{
if (a != null)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.Append(a.OriginalString);
}
}
TraceUtility.TraceString(TraceEventType.Error, sb.ToString());
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(SR.GetString(SR.ID1037)));
}
}
}
示例6: ExtractSite
public static void ExtractSite()
{
var siteConfig = GetConfigFile();
var pageElements = siteConfig.Descendants("page");
if (pageElements.Any())
{
//Create export folder
long folderTimeStamp = DateTime.Now.Ticks;
string exportFolderPath = HttpContext.Current.Server.MapPath(@"/Export" + "/" + folderTimeStamp + "/");
Directory.CreateDirectory(exportFolderPath);
//Create our html pages
using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
{
Uri uri = new Uri(HttpContext.Current.Request.Url.ToString());
var sitePath = uri.GetLeftPart(UriPartial.Authority) + "/";
//Set close tag options for html agility pack
HtmlNode.ElementsFlags["option"] = HtmlElementFlag.Closed;
foreach (var page in pageElements)
{
string pagePath = sitePath + page.Value;
string newFileName = page.Value.Replace("cshtml", "html");
//Load our web page and replace all references to cshtml with html for links
string pageHtml = client.DownloadString(pagePath).Replace("cshtml", "html");
//Convert our html string to a doc to amend
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(pageHtml);
var currentPageLinks = htmlDoc.DocumentNode.SelectNodes("//nav/descendant::a[@href='" + newFileName + "']");
if (currentPageLinks != null)
{
foreach (var link in currentPageLinks)
{
//Add selected class to parent node
link.ParentNode.Attributes.Add("class", "selected");
}
}
htmlDoc.Save(exportFolderPath + newFileName);
}
}
//Custom files required
var files = siteConfig.Descendants("file");
foreach (var file in files)
{
var filePath = HttpContext.Current.Server.MapPath(@"/" + file.Value);
File.Copy(filePath, exportFolderPath + file.Value);
}
//Copy all our folders we need
var folders = siteConfig.Descendants("folder");
foreach (var folder in folders)
{
string folderName = folder.Value;
string folderPath = HttpContext.Current.Server.MapPath(@"/" + folderName);
//Create folder path
Directory.CreateDirectory(exportFolderPath + folderName);
//Create all sub folders
foreach (string dirPath in Directory.GetDirectories(folderPath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(folderPath, exportFolderPath + folderName));
//Copy all the files
foreach (string newPath in Directory.GetFiles(folderPath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(folderPath, exportFolderPath + folderName));
}
}
}
示例7: RemoveQueryStringByKey
public static string RemoveQueryStringByKey(Uri uri, string key)
{
// this gets all the query string key value pairs as a collection
var newQueryString = HttpUtility.ParseQueryString(uri.Query);
// this removes the key if exists
newQueryString.Remove(key);
// this gets the page path from root without QueryString
string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
return newQueryString.Count > 0
? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
: pagePathWithoutQueryString;
}
示例8: GetOperationName
public static string GetOperationName(Uri requestUri, Uri baseAddress)
{
try
{
// remove the query part as they are irrelevant here and we dont want to fail parsing them.
Uri requestUriWithoutQuerypart = new Uri(requestUri.GetLeftPart(UriPartial.Path));
SyntacticTree syntacticTree = SyntacticTree.ParseUri(requestUriWithoutQuerypart, baseAddress);
SegmentQueryToken lastSegment = syntacticTree.Path as SegmentQueryToken;
if (lastSegment != null && !String.IsNullOrEmpty(lastSegment.Name))
{
return lastSegment.Name;
}
}
catch (Exception)
{
}
return null;
}
示例9: GetCallbackUrl
private static String GetCallbackUrl(String providerId, Uri requestUri)
{
return String.Format("{0}{1}/UserOptions.aspx?oauthCallback=true&providerId={2}", requestUri.GetLeftPart(UriPartial.Authority), HttpRuntime.AppDomainAppVirtualPath, providerId);
}
示例10: Create
/// <summary>
/// This function is used in both parser and f&o library, so just strictly map valid literals to XmlCollation.
/// Set compare options one by one:
/// 0, false: no effect; 1, true: yes
/// Disregard unrecognized options.
/// </summary>
internal static XmlCollation Create(string collationLiteral) {
Debug.Assert(collationLiteral != null, "collation literal should not be null");
if (collationLiteral == XmlReservedNs.NsCollCodePoint) {
return CodePointCollation;
}
XmlCollation coll = new XmlCollation();
Uri collationUri = new Uri(collationLiteral);
string authority = collationUri.GetLeftPart(UriPartial.Authority);
if (authority == XmlReservedNs.NsCollationBase) {
// Language
// at least a '/' will be returned for Uri.LocalPath
string lang = collationUri.LocalPath.Substring(1);
if (lang.Length == 0) {
// Use default culture of current thread (cultinfo = null)
} else {
// Create culture from RFC 1766 string
try {
coll.cultinfo = new CultureInfo(lang);
}
catch (ArgumentException) {
throw new XslTransformException(Res.Coll_UnsupportedLanguage, lang);
}
}
} else if (collationUri.IsBaseOf(new Uri(XmlReservedNs.NsCollCodePoint))) {
// language with codepoint collation is not allowed
coll.compops = CompareOptions.Ordinal;
} else {
// Unrecognized collation
throw new XslTransformException(Res.Coll_Unsupported, collationLiteral);
}
// Sort & Compare option
// at least a '?' will be returned for Uri.Query if not empty
string query = collationUri.Query;
string sort = null;
if (query.Length != 0) {
foreach (string option in query.Substring(1).Split('&')) {
string[] pair = option.Split('=');
if (pair.Length != 2)
throw new XslTransformException(Res.Coll_BadOptFormat, option);
string optionName = pair[0].ToUpper(CultureInfo.InvariantCulture);
string optionValue = pair[1].ToUpper(CultureInfo.InvariantCulture);
if (optionName == sortStr) {
sort = optionValue;
}
else if (optionValue == "1" || optionValue == "TRUE") {
switch (optionName) {
case ignoreCaseStr: coll.compops |= CompareOptions.IgnoreCase; break;
case ignoreKanatypeStr: coll.compops |= CompareOptions.IgnoreKanaType; break;
case ignoreNonspaceStr: coll.compops |= CompareOptions.IgnoreNonSpace; break;
case ignoreSymbolsStr: coll.compops |= CompareOptions.IgnoreSymbols; break;
case ignoreWidthStr: coll.compops |= CompareOptions.IgnoreWidth; break;
case upperFirstStr: coll.upperFirst = true; break;
case emptyGreatestStr: coll.emptyGreatest = true; break;
case descendingOrderStr: coll.descendingOrder = true; break;
default:
throw new XslTransformException(Res.Coll_UnsupportedOpt, pair[0]);
}
}
else if (optionValue == "0" || optionValue == "FALSE") {
switch (optionName) {
case ignoreCaseStr: coll.compops &= ~CompareOptions.IgnoreCase; break;
case ignoreKanatypeStr: coll.compops &= ~CompareOptions.IgnoreKanaType; break;
case ignoreNonspaceStr: coll.compops &= ~CompareOptions.IgnoreNonSpace; break;
case ignoreSymbolsStr: coll.compops &= ~CompareOptions.IgnoreSymbols; break;
case ignoreWidthStr: coll.compops &= ~CompareOptions.IgnoreWidth; break;
case upperFirstStr: coll.upperFirst = false; break;
case emptyGreatestStr: coll.emptyGreatest = false; break;
case descendingOrderStr: coll.descendingOrder = false; break;
default:
throw new XslTransformException(Res.Coll_UnsupportedOpt, pair[0]);
}
}
else {
throw new XslTransformException(Res.Coll_UnsupportedOptVal, pair[0], pair[1]);
}
}
}
// upperfirst option is only meaningful when not ignore case
if (coll.upperFirst && (coll.compops & CompareOptions.IgnoreCase) != 0)
coll.upperFirst = false;
// other CompareOptions are only meaningful if Ordinal comparison is not being used
if ((coll.compops & CompareOptions.Ordinal) != 0) {
coll.compops = CompareOptions.Ordinal;
coll.upperFirst = false;
//.........这里部分代码省略.........