本文整理汇总了C#中System.Uri.GetLeftPart方法的典型用法代码示例。如果您正苦于以下问题:C# Uri.GetLeftPart方法的具体用法?C# Uri.GetLeftPart怎么用?C# Uri.GetLeftPart使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Uri
的用法示例。
在下文中一共展示了Uri.GetLeftPart方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: createHttpRequest
static void createHttpRequest(IFakeAccessor context)
{
// MvcContrib.FakeHttpRequest doesn't implement RawUrl.
var uri = new Uri(_currentUrl);
context.The<HttpRequestBase>().WhenToldTo(x => x.Url).Return(uri);
context.The<HttpRequestBase>().WhenToldTo(x => x.RawUrl)
.Return(uri.AbsoluteUri.Substring(uri.GetLeftPart(UriPartial.Authority).Length));
// Used by PathHelpers.GenerateClientUrl(...)
context.The<HttpRequestBase>().WhenToldTo(x => x.ApplicationPath).Return("/");
}
示例2: Build
public string Build(Uri uri)
{
if (_qs.Count <= 0)
return uri.GetLeftPart(UriPartial.Path);
List<string> qs = new List<string>();
foreach (var kv in _qs.Where(x => !string.IsNullOrEmpty(x.Key)))
qs.Add(kv.Key + "=" + HttpUtility.UrlEncode(kv.Value));
if(qs.Count > 0)
return uri.GetLeftPart(UriPartial.Path) + "?" + string.Join("&", qs);
else
return uri.GetLeftPart(UriPartial.Path);
}
示例3: Build
public static string Build(string href, Uri uri)
{
if (href.StartsWith("http"))
return href;
return string.Format("{0}{1}{2}", uri.GetLeftPart(UriPartial.Scheme), uri.Authority, href);
}
示例4: Should_remove_username_and_password_from_source_address
public void Should_remove_username_and_password_from_source_address()
{
var inputAddress = new Uri("rabbitmq://testUser:[email protected]/mt/test_queue");
var sourceAddress = new Uri("rabbitmq://localhost/mt/test_queue");
var future = new Future<IConsumeContext<A>>();
using (IServiceBus bus = ServiceBusFactory.New(c =>
{
c.ReceiveFrom(inputAddress);
c.UseRabbitMq(r =>
{
r.ConfigureHost(sourceAddress, h =>
{
h.SetUsername("testUser");
h.SetPassword("test");
});
});
c.Subscribe(s => s.Handler<A>((context, message) => future.Complete(context)));
}))
{
bus.Publish(new A());
Assert.IsTrue(future.WaitUntilCompleted(TimeSpan.FromSeconds(8)));
}
Assert.AreEqual(sourceAddress.ToString(), future.Value.SourceAddress.ToString());
Assert.AreEqual(sourceAddress.GetLeftPart(UriPartial.Authority),
future.Value.DestinationAddress.GetLeftPart(UriPartial.Authority));
}
示例5: Login
public ActionResult Login(LoginModel model, string returnUrl)
{
// No checking of password for this sample. Just care about the username
// as that's what we're including in the token to send back to the authorization server
// Corresponds to shared secret the authorization server knows about for this resource
const string encryptionKey = "WebAPIsAreAwesome";
// Build token with info the authorization server needs to know
var tokenContent = model.UserName + ";" + DateTime.Now.ToString(CultureInfo.InvariantCulture) + ";" + model.RememberMe;
var encryptedToken = EncodingUtility.Encode(tokenContent, encryptionKey);
// Redirect back to the authorization server, including the authentication token
// Name of authentication token corresponds to that known by the authorization server
returnUrl += (returnUrl.Contains("?") ? "&" : "?");
returnUrl += "resource-authentication-token=" + encryptedToken;
var url = new Uri(returnUrl);
var redirectUrl = url.ToString();
// URL Encode the values of the querystring parameters
if (url.Query.Length > 1)
{
var helper = new UrlHelper(HttpContext.Request.RequestContext);
var qsParts = HttpUtility.ParseQueryString(url.Query);
redirectUrl = url.GetLeftPart(UriPartial.Path) + "?" + String.Join("&",qsParts.AllKeys.Select(x => x + "=" + helper.Encode(qsParts[x])));
}
return Redirect(redirectUrl);
}
示例6: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
var uri = new Uri(Request.Url.ToString());
string path = uri.GetLeftPart(UriPartial.Path);
if (!(((string)Session["loginName"]) != null && !(((string)Session["loginName"]).Equals(""))))
{
post.InnerHtml = "";
}
string paramThread = Request.QueryString["thread"];
if (paramThread != null)
{
test.Text += loadThread(Convert.ToInt32(paramThread));
}
else
{
test.Text = "<div class=\"jumbotron\"><div class=\"container\"><h1>Bienvenue Pirates!</h1><p>C'est le temps de se parler!</p></div></div>";
test.Text += loadIndex();
post.InnerHtml = "";
if (((string)Session["loginName"]) != null && !((string)Session["loginName"]).Equals(""))
{
test.Text += "<h2><a href=\"NewThread.aspx\">Créer un nouveau sujet!</a></h2>";
}
}
}
示例7: Run
private static void Run(string[] args)
{
Arguments arguments;
try
{
arguments = Arguments.Parse(args);
}
catch (Exception e)
{
throw new ArgumentException(string.Format("Error parsing arguments: {0}", e.Message), e);
}
string urlString = arguments.Url;
if (urlString == null)
throw new ArgumentException("Url to API has to be specified.");
if (!urlString.StartsWith("http"))
urlString = "http://" + urlString;
var url = new Uri(urlString, UriKind.Absolute);
string baseUrl = url.GetLeftPart(UriPartial.Authority);
string apiPath = url.AbsolutePath;
if (apiPath == "/")
apiPath = "/w/api.php";
var wiki = new Wiki(baseUrl, apiPath, arguments.Namespace, arguments.PropsFile);
wiki.AddAllModules();
wiki.AddAllQueryModules();
var result = wiki.Compile(arguments.OutputName, arguments.Directory);
foreach (CompilerError error in result.Errors)
Console.WriteLine(error);
}
示例8: DownloadImage
public static string DownloadImage(string urlImage, string fileName)
{
string remoteImgPath = urlImage;
try
{
var remoteImgPathUri = new Uri(remoteImgPath);
string remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);
string fileExtension = Path.GetExtension(remoteImgPathWithoutQuery); // .jpg, .png
string folder = DateTime.Now.ToString("yyyyMMdd");
string uploadPath = AppDomain.CurrentDomain.BaseDirectory + "Images\\I\\" + folder;
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string localPathFull = AppDomain.CurrentDomain.BaseDirectory + "Images\\I\\" + folder + "\\" + fileName + fileExtension;
var webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPathFull);
return "images/I/" + "/" + folder + "/" + fileName + fileExtension;
}
catch (Exception ex)
{
return ConstantManager.DefaultImage;
}
}
示例9: FormatAbsoluteUrl
public static String FormatAbsoluteUrl(String relativeUrl, String baseUrl)
{
if (relativeUrl.Contains("http"))
{
return relativeUrl;
}
int askIndex = baseUrl.IndexOf('?');
if (askIndex >= 0)
{
baseUrl = baseUrl.Substring(0, askIndex);
}
if (relativeUrl.StartsWith("/"))
{
Uri baseUri = new Uri(baseUrl);
return String.Format("{0}{1}", baseUri.GetLeftPart(UriPartial.Authority), relativeUrl);
}
else
{
if (!baseUrl.EndsWith("/"))
{
baseUrl = String.Format("{0}/", baseUrl);
}
Uri baseUri = new Uri(baseUrl);
return String.Format("{0}{1}", baseUri.GetLeftPart(UriPartial.Path), relativeUrl);
}
}
示例10: GetAdfsConfigurationFromTargetUri
public static void GetAdfsConfigurationFromTargetUri(Uri targetApplicationUri, out string adfsHost, out string adfsRelyingParty)
{
adfsHost = "";
adfsRelyingParty = "";
var trustEndpoint = new Uri(new Uri(targetApplicationUri.GetLeftPart(UriPartial.Authority)), "/_trust/");
var request = (HttpWebRequest)WebRequest.Create(trustEndpoint);
request.AllowAutoRedirect = false;
try
{
using (var response = request.GetResponse())
{
var locationHeader = response.Headers["Location"];
if (locationHeader != null)
{
var redirectUri = new Uri(locationHeader);
Dictionary<string, string> queryParameters = Regex.Matches(redirectUri.Query, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => Uri.UnescapeDataString(x.Groups[3].Value));
adfsHost = redirectUri.Host;
adfsRelyingParty = queryParameters["wtrealm"];
}
}
}
catch (WebException ex)
{
throw new Exception("Endpoint does not use ADFS for authentication.", ex);
}
}
示例11: HandleRequest
protected override bool HandleRequest(string url, ref byte[] responseBody, ref string[] responseHeaders)
{
var uri = new Uri(url);
var path = uri.GetLeftPart(UriPartial.Path).Replace(Scheme, "");
if (path.EndsWith("/"))
path = path.Substring(0, path.Length - 1);
var stream = OpenFile(path);
if (stream == null) {
responseHeaders = new string[] {
"HTTP/1.1 404 Not Found"
};
return false;
}
using (stream) {
responseBody = new byte[stream.Length];
stream.Read(responseBody, 0, responseBody.Length);
}
var mimeType = SelectMimeType(path);
responseHeaders = new string[] {
"HTTP/1.1 200 OK",
String.Format("Content-type: {0}; charset=utf-8", mimeType)
};
return true;
}
示例12: EncodeUri
public static string EncodeUri(Uri uri)
{
if (!uri.IsAbsoluteUri)
{
var uriString = uri.IsWellFormedOriginalString() ? uri.ToString() : Uri.EscapeUriString(uri.ToString());
return EscapeReservedCspChars(uriString);
}
var host = uri.Host;
var encodedHost = EncodeHostname(host);
var needsReplacement = !host.Equals(encodedHost);
var authority = uri.GetLeftPart(UriPartial.Authority);
if (needsReplacement)
{
authority = authority.Replace(host, encodedHost);
}
if (uri.PathAndQuery.Equals("/"))
{
return authority;
}
return authority + EscapeReservedCspChars(uri.PathAndQuery);
}
示例13: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
CheckLogin();
if (!ClientScript.IsStartupScriptRegistered("JsFunc_DefaultSize"))
Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFunc_DefaultSize", "DefaultSize();", true);
if (!IsPostBack)
{
if (Request.UrlReferrer != null)
{
var uri = new Uri(Request.UrlReferrer.ToString());
prevPage = uri.GetLeftPart(UriPartial.Path);
}
if (Session["Test_dtmember"] != null && prevPage.Contains("/Master/SingleMember.aspx"))
{
if (!ClientScript.IsStartupScriptRegistered("JsFunc_Setsize"))
Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFunc_Setsize", "Setsize();", true);
GridViewPlan.DataSource = (DataTable)Session["Test_dtmember"];
GridViewPlan.DataBind();
}
//Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFun", "DefaultSize()", true);
DataTable dtFellowship = CobcYouthDAL.GetFellowship();
dpFellowship.DataSource = dtFellowship;
dtFellowship.Rows.Add(0, "全部團契");
dtFellowship.DefaultView.Sort = "FellowshipID";
dpFellowship.DataValueField = "FellowshipID";
dpFellowship.DataTextField = "name";
dpFellowship.DataBind();
}
}
示例14: TranslateHref
public static bool TranslateHref(string pageURL, string href, out string translatedURL)
{
string lwhref = LowerString(href);
var opageurl = new Uri(pageURL);
Uri otranslatedurl = null;
translatedURL = null;
if (string.IsNullOrEmpty(href))
{
return false;
}
if (lwhref.StartsWith("//", StringComparison.InvariantCultureIgnoreCase))
{
translatedURL = opageurl.Scheme + ":" + href;
}
else if (lwhref.StartsWith("http", StringComparison.InvariantCultureIgnoreCase) || lwhref.StartsWith("https", StringComparison.InvariantCultureIgnoreCase))
{
translatedURL = href;
}
else
{
translatedURL = opageurl.GetLeftPart(UriPartial.Authority);
if(!href.StartsWith("/"))
{
translatedURL += "/";
}
translatedURL += href;
}
return Uri.TryCreate(translatedURL, UriKind.Absolute, out otranslatedurl);
}
示例15: For
/// <summary>
/// Return a fake RequestContext that can be used to create a stub UrlHelper
/// </summary>
/// <param name="url">Url to fake a request for.</param>
internal static RequestContext For(string url)
{
if (_specificationController == null)
throw new InvalidOperationException(
"Test context must inherit 'WithFakes' to use FakeUrlHelper or FakeRequestContext.");
// MvcContrib.FakeHttpRequest doesn't implement RawUrl.
var request = An<HttpRequestBase>();
var uri = new Uri(url);
request.WhenToldTo(x => x.Url).Return(uri);
request.WhenToldTo(x => x.RawUrl).Return(uri.AbsoluteUri.Substring(uri.GetLeftPart(UriPartial.Authority).Length));
// Used by PathHelpers.GenerateClientUrl(...)
request.WhenToldTo(x => x.ApplicationPath).Return("/");
var httpContext = An<HttpContextBase>();
httpContext.WhenToldTo(x => x.Request).Return(request);
// Used by RouteCollection.GetUrlWithApplicationPath(...)
httpContext.WhenToldTo(x => x.Response).Return(new FakeHttpResponse());
var routeData = An<RouteData>();
var requestContext = An<RequestContext>();
requestContext.WhenToldTo(x => x.HttpContext).Return(httpContext);
// Used by UrlHelper.GenerateUrl(...)
requestContext.WhenToldTo(x => x.RouteData).Return(routeData);
return requestContext;
}