in asp.net-mvc, how can i build up URLs in controller - c#

if my current controller, my URL is:
http://test.mysite.com/Person/Detail/1
how can i extract into a variable:
Full URL (http://test.mysite.com/Person/Detail/1)
Root url (http://test.mysite.com)
i am sending links inside of emails so i can't just use relative URLs (that why i need something that will get me these URLs

var fullUrl = Request.RawUrl;.
var rootUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Have a look at this answer it may be of use:
How can I return the current action in an ASP.NET MVC view?
The Uri object is useful when working with URLs also

Related

looking for Another way to call WebAPI Controller

Is there any way by which I can replace http://localhost:12345 while calling the WebAPI controller?
For Eg: For calling Controller we create URL like http://localhost:12345/api/Home?id=5 .. I do not want that.
I want my code to create http://localhost:12345 for me as string.
I had look around and I got this string baseURL = HttpContext.Current.Request.Url.Host; but it is only giving me localhost as an string.
In this statement Uri uri = new Uri("http://localhost:12345/api/Home?id=5"); we are passing URL to call controller. In my case, I want my this http://localhost:12345 part of URL should be created dynamically.
Can anyone suggest other way around?
Thank You
This did my Job.
var request = HttpContext.Current.Request;
var builder = new UriBuilder(request.Url.Scheme, request.Url.Host, request.Url.Port);
return builder.ToString();

How pass url params to route?

I add route to project.All work correct, but if i send normal url as first param its not correctly work.
Get["/{url}/{digit}"
If i send this params to server-all work correctly.
localhost:8888/google.com/2
But if i send param with http://www its not work.
localhost:8888/https://www.google.com/2
How correct pass url param to route? I think it because Nancy think that i send 3 input param.
If you really need to use GET instead of POST try HttpUtility.UrlEncode("https://google.com/2") to urlencode your url.
You have to encode your url which is send as a paramater:
Use:
var encodedString = Uri.EscapeDataString("https://www.google.com/2");
then your url will look like this and it shouldn't get any errors:
https%3A%2F%2Fwww.google.com%2F2
Sending the request:
localhost:8888/https%3A%2F%2Fwww.google.com%2F2
Or ou can use the
HttpUtility.UrlEncode();
method. For further information have a look at this.
Since you insist on changing the backend only, you could try using a regex to capture your route
Get["^(?<url>.*<digit>[0-9]+)$"]
This should match any url ending with atleast one number, and put everything before it in url like so:
Get["^(?<url>.*<digit>[0-9]+)$"] = parameters =>
{
var url = parameters.url;
var digit = parameters.digit;
};
I am currently unable to verify if this works as you want it to though, and to make sure you can adjust this yourself make sure to look into how to write regex

Should a .Net protocol-less URI showing as relative?

All,
In HTML, it is my understanding that a url that starts // (e.g. //www.google.com) refers to a protocol-less url that should be requested in the same scheme as that in which the page was served.
However, the following c# code fails
var uri = new Uri("//www.google.com", UriKind.RelativeOrAbsolute);
Assert.IsTrue(uri.IsAbsoluteUri);
Am I missing something here? At the moment I am rolling my own regex to find out if a URI is absolute:
return Regex.IsMatch(url, #"^(https?:)?//")
It's not absolute. It's relative to whether the URL is accessed from a source that is served over HTTP, HTTPS, or something else.

HttpWebRequest not being received correctly in MVC ASP.NET

This is me publicly documenting my mistake so that if I or anyone does it again, they don't have to spend 3 hours tearing their hair out trying to fix such a simple thing.
Context
I was sending an HttpRequest from one C# MVC ASP.NET application to another.
The applications require an HTTPS connection, and we are using URLRewrite to redirect an HTTP request to an HTTPS url.
One application was sending a POST request with some JSON data in the body, pretty standard stuff. The other application was set up to receive this data with an MVC controller class (CollectionAction and Insert methods for GET and POST respectively).
Symptoms of the problem
The receiving application was running the GET method (CollectionAction) instead of the POST action (ItemAction). The reason for this was that the request coming in to the application was in fact a GET request, and to top it off the JSON data was missing too.
I sent the header "x-http-method" to override the request method from GET to POST (I was already setting the request httpmethod to POST but this was being ignored). This worked but still I had no data being sent.
So now I am stuck pulling my hair out, because I can see a POST request with content-length and data being sent out and I have a GET request with no data or content-length coming in (but the headers were preserved)
Turns out I was using UriBuilder to take a base URL and apply a resource path to it. For example I would have "google.com" in my web.config and then the UriBuilder would take a resource like Pages and construct the url "google.com/Pages". Unfortunately, I was not initializing the UriBuilder with the base URL, and instead was using a second UriBuilder to extract the host and add that to the path like so:
public Uri GetResourceUri(string resourceName)
{
var domain = new UriBuilder(GetBaseUrl());
var uribuilder = new UriBuilder()
{
Path = domain.Path.TrimEnd('/') + "/" + resourceName.TrimStart('/'),
Host = domain.Host
};
var resourceUri = uribuilder.Uri;
return resourceUri;
}
The problem with this code is that the scheme is ignored (HTTP:// vs HTTPS://) and it defaults to HTTP. So my client was sending out the request to an HTTP url instead of the required HTTPS url. This is the interesting part, URLRewrite was kicking in and saying that we needed to go to an HTTPS url instead so it redirected us there. But in doing so, it ignored the Http-Method and the POST data, which just got set to defaults GET and null. This is what the 2nd application could see at the receiving end.
So the function had to be rewritten to this which fixed the problem:
public Uri GetResourceUri(string resourceName)
{
var baseUrl = GetBaseUrl();
var domain = new UriBuilder(baseUrl);
var uribuilder = new UriBuilder(baseUrl)
{
Path = domain.Path.TrimEnd('/') + "/" + resourceName.TrimStart('/'),
};
var resourceUri = uribuilder.Uri;
return resourceUri;
}

unshortening urls

I am trying to unshorten urls and have not been able to find code (vb.net/c#) to do this. These are the twitter shortened urls and I guess I could try and access one of the web services available and do a httpwebrequest but would prefer to find some programmatic way of doing this.
You can get it directly from response of the shortened url since it will return a status code MovedPermanently and the location for the real url.(This should work for most of the sites without the need for navigating to the real url)
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://t.co/xqbLEi6s");
req.AllowAutoRedirect = false;
var resp = req.GetResponse();
string realUrl = resp.Headers["Location"];
Other test data: http://goo.gl/zdf2n , http://tinyurl.com/8xc9vca , http://x.co/iEup, http://is.gd/vTOlz6 , http://bit.ly/FUA4YU
There is no magic way to unshorten a URL without asking the service which created the URL (and the way to ask will be different for each service), or more pragmatically, just opening the URL and watching where it redirects to.

Categories

Resources