Setting HttpContext.Current.Request.Url.Host - asp.net

I need to replace the host part of the Uri
HttpContext.Current.Request.Url.Host = "newDomain";
you can't set host. Is there a quick and easy way to do this to a Uri for reusing it to redirect somewhere else?

Use the UriBuilder class to change URIs, e.g.
var original = HttpContext.Current.Request.Url;
var changed = (new UriBuilder(original) { Host = "newDomain" }).Uri;
URIs are tricky little beasts with plenty of semantics you might not know or expect, so don't go using string functions on them unless you absolutely have to.

Related

A good name for a URL path and query string and fragment?

URLs can be broken up into these components:
Sample URL: http://www.server.com:8080/path?query=string#fragment
protocol = http
host = www.server.com
port = 8080
path = /path
query = ?query=string
fragment = #fragment
Is there an established name for everything that comes after port (path, query, and fragment)? I was tempted to just call this "path" but that is not a good name as it does not include the query and fragment.
The IETF URI Spec defines the combination of these elements (path, query, and fragment) as a Relative Reference.
Perhaps "relative URL", as in "relative to Site Root"
The URL structure you are giving is containing the basic elements, and the fragment is usually coming before the query, the query in general is used when you are listing a part of data, so you need to access to it by this query, and parameters if needed.
Here a good review to list the steps for creating a good url.
there is no established name for everything together due to them all being different. Also you forgot the parameters part of the url. The parameters go in the query.

Apigee remove URL string before forwarding request to target

I want to transform a URL before it is redirected to the target, removing a string. I have the following flow in Apigee:
USER -> APIGEE -> APPLICATION -> APIGEE -> USER
The user requests and then its URL should be rewritten removing bar from the URL.
BEFORE apigee.url.com/foo/bar/pBxATaojIn8tk5dvQdNJ
AFTER target.url.com/foo/pBxATaojIn8tk5dvQdNJ
I use Proxy Endpoints and Target Endpoints and try to rewrite using a PreFlow hook with Javascript in the Target Endpoint, without success rewriting the proxy.pathsuffix. How can I solve this?
I now use the following solution:
// Disable copy path
context.setVariable("target.copy.pathsuffix", false);
// Replace string in incoming proxy URL path
var proxyPathSuffix = context.getVariable("proxy.pathsuffix");
var fooBarAfter = proxyPathSuffix.replace('/fooToReplace', '');
// Fetch target outgoing url path
var targetBasePath = context.getVariable("target.basepath");
var urlPath = targetBasePath.concat(fooBarAfter);
// Replace outgoing url
var targetUrl = context.getVariable("target.url");
targetUrl = targetUrl.replace(targetBasePath, urlPath);
context.setVariable("target.url", targetUrl);
I came up with it looking at the available variables here. As this is JS, if someone comes up with a better solution I would be happy!
From my understanding proxy.pathsuffix is a read only variable so you can't override it.
Assign your target endpoint to target.url instead. (I usually use in Assign Message Policy of the request)
Example:
<AssignVariable>
<Name>target.url</Name>
<Ref>yourTargetUrlValue</Ref>
</AssignVariable>
In my Assign Message Policy of the request, I have added the block of code above for defined my target url.
You can assign directly like <Ref>http://test.com</Ref> or assign via variable like <Ref>{targetUrlVal}</Ref>
If you got the url from somewhere, don't forget to assign value to your variable before use it by using context.setVariable("targetUrlVal", "http://test-01.com");
Hopefully my answer will help you.
I solved this similar to how you did it. See my answer on another SO question that answers this.

How to write a link to an Alfresco Share folder? (within a site)

I want to create an HTTP link to a particular folder in Alfresco Share.
Alfresco Share encodes paths in a rather convoluted way:
thesite
http://server/share/page/site/thesite/documentlibrary
thesite/documentLibrary/somefolder/anotherfolder
http://server/share/page/site/thesite/documentlibrary#filter=path|%2Fsomefolder%2Fanotherfolder
thesite/documentLibrary/éß和ệ
http://server/share/page/site/s1/documentlibrary#filter=path|%2F%25E9%25DF%25u548C%25u1EC7
thesite/documentLibrary/a#bc/éß和ệ
http://server/share/page/site/thesite/documentlibrary#filter=path%7C%2Fa%2523bc%2F%25E9%25DF%25u548C%25u1EC7%7C
I suspect it is a double URLencode, with the exception of slashes which are only URLencoded once.
But I am not 100% sure.
Is there a C# library that does this encoding?
You might find it easier to use the legacy ?path= parameter for document library folder URL creation.
Using the example path /Sample Content/∞⊕⊗¤☺☹★☆★☆★ instead of building a URL of the form
http://alfresco.example/share/page/site/mike/documentlibrary#filter=path%7C%2FSample%2520Content%2F%25u221E%25u2295%25u2297%25A4%25u263A%25u2639%25u2605%25u2606%25u2605%25u2606%25u2605%7C&page=1
you can generate one that looks like
https://alfresco.example/share/page/site/mike/documentlibrary?path=/Sample%20Content/%E2%88%9E%E2%8A%95%E2%8A%97%C2%A4%E2%98%BA%E2%98%B9%E2%98%85%E2%98%86%E2%98%85%E2%98%86%E2%98%85
So using C# you'd use Uri.EscapeUriString() on the path and append it to the base document library URL with ?path=
You can see how the path parameter is interpreted in documentlibrary.inc.ftl
Check org.alfresco.repo.web.scripts.site.SiteShareViewUrlGetfor an implementation. Its not very elegant, but seems pretty complete, probably a good starting point for your own class.
There really should be a helper class for this, but maybe I'm missing something.
I could not find a library, so I wrote the following code:
if (path.Contains("documentLibrary"))
{
int firstSlashPosition = path.IndexOf("/");
string siteName = path.Substring(0, firstSlashPosition);
string pathWithinSite = path.Substring(firstSlashPosition + "/documentLibrary".Length);
string escapedPathWithinSite = HttpUtility.UrlEncode(pathWithinSite);
string reescapedPathWithinSite = HttpUtility.UrlEncode(escapedPathWithinSite);
string sharePath = reescapedPathWithinSite.Replace("%252f", "%2F");
return "http://server/share/page/site/" + siteName + "/documentlibrary#filter=path|" + sharePath;
}
else
{
// Site name only.
return "http://server/share/page/site/" + path + "/documentlibrary";
}
Any correction or better answer would be much appreciated!

How to Generate absolute urls with https in MVC3?

I am using MVC3 and am trying to serve content from https, the problem is that when I call Url.Content the files are still served from http using a relative url. I thought this problem was addressed in MVC3 but i can't seem to find any solution. Does anybody know if this issue is inherently solved in MVC3 and how to accomplish it or do I need to create my own helper methods to generate absolute Urls based on protocol?
You can probably implement your own solution using VirtualPathUtility.ToAbsolute. Probably something like this:
public static class UrlHelperExtension {
public static string Absolute(this UrlHelper url, string relativeOrAbsolute) {
var uri = new Uri(relativeOrAbsolute, UriKind.RelativeOrAbsolute);
if (uri.IsAbsoluteUri) {
return relativeOrAbsolute;
}
// At this point, we know the url is relative.
return VirtualPathUtility.ToAbsolute(relativeOrAbsolute);
}
}
which you would use like:
#Url.Absolute(Url.Content("~/Content/Image.png"))
(Didn't test this myself, feel free to play around to make it work right.)
This helps to you to generate absolute URLs for your content files. In order to change the scheme of the resulting URLs, you can create an additional extension method that manipulates the scheme of the given URLs so that they are HTTPS, or something else.
As Khalid points out in the comments, similar extension methods are already available in various open-source projects which you can make use of (given that the license permits). An example one can be found here.
A solution that doesn't use extension methods or hardcode the protocol, as suggested by #BlackTigerX:
Url.RouteUrl("Default", new { Action = "About" }, Request.Url.Scheme)
as suggested in the following article: http://captaincodeman.com/2010/02/03/absolute-urls-using-mvc-without-extension-methods/
You can use Url.RouteUrl, some of the overloads take a protocol parameter, looks something like this:
Url.RouteUrl("Product", new { itemId = "123456" }, "https");
Take a look a the overloads and see which one you can use
If you don't want to "build" the url and just want the full path of the current page, this will do the trick
Context.Server.UrlEncode(Context.Request.Url.AbsoluteUri)
I know it's not as elegant as an Extension Method but thought of sharing it for educational purposes

URLRewriting challenge

I'm using URLRewritingNet 2.0. How do I rewrite URL's in ASP.NET?
Here is the request:
Input: www.sampleweb.com/param1/value1/param2/value2/default.aspx
Output: www.sampleweb.com/default.aspx?param1=value1&param2=value2
It must work dynamically like this param1/value1/param2/value2/ ... /paramN/valueN
That is not a good way to pass key/value pairs.
You should assume the key based on the values position. That makes life a lot easier. HttpContext.RewritePath (with its variations) is how you go about transforming the url.
So...basically you can't do this in the "rewrite" node in your web.config file using ASP.Net's URL Rewriter.
But you could do it elsewhere in your code (an HTTP Module, or Begin Request, or whatever). To transform you URL's you could do something like this:
string strRegex= #"/([^/]*)/([^/]*)";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = #"/param1/value1/param2/value2/param3/value3/param4/value4";
string strReplace = #"$1=$2&";
If you combine that with matching the filename (here's the RE):
(.*)/([^/]*\..*)$
And then re-composing the complete URL--then you could Server.Execute or whatever (if on your own server) or otherwise proxy over to where you want this processed. Yup, it's a little ugly, but if you don't have control of the shape of the request coming at you, this is a way to transform it.

Resources