How to Generate absolute urls with https in MVC3? - asp.net

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

Related

Explanation for url() function Drupal 8

I'm very new to drupal and have to do some real quick small work. While going through the documentation at https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates, I saw string parameter to url() function.
{{ 'View all content'|t }}
what is the value that url() is taking?
Infact, i'm trying to get relative path. I used
Solutions
But, it didn't work for me because {{directory}} changed each time and led to url append. Is there any best practices? Thank you for suggestions.
When adding a URL into a string, for instance in a text description, core recommends we use the \Drupal\Core\Url class. This has a few handy methods:
Internal URL based on a route - Url::fromRoute(), Example: Url::fromRoute('acquia_connector.settings')
Internal URL based on a path - Url::fromInternalUri(), Example: Url::fromInternalUri('node/add')
External URL - Url::fromUri, Example: Url::fromUri('https://www.acquia.com')
The last two methods are very similar, the main difference is, that fromInternalUri() already assumes an 'internal:' prefix, which tells Drupal to build an internal path. It's worth reading up on what prefixes are supported, for instance the ':entity' prefix can help in building dynamic URIs.
When you need to constrict and display the link as text you can use the toString() method: Url::fromRoute('acquia_connector.settings')->toString().
If you need additional information please ask.

Symfony2 GenerateURL to a complex route

This seems like the dumbest question ever, but I can't seem to figure it out. I have a page the needs to redirect to a complex route and I can't seem to generate the URL. Redirecting to a simple route is easy enough:
return $this->redirect($this->generateUrl('testnumber'));
However, I want to route to: testnumber/1/question/4. How can I accomplish this incredibly simple task? The only thing I have found in the documentation and Google allows me to add parameters and not just create a complex route. For example:
generateURL('testnumber', array('testid'=>1, 'question'=>4))
makes a URL of /testnumber?testid=1&question=4, which I do not want.
Edit: Yes, I already have the route created in a YML file. I simply cannot generate the URL to link to it.
return $this->redirect($this->generateUrl(???????????),true));
This is my route:
#Route("/testnumber/{testid}/question/{question}", name="testnumber")
The Symfony documentation only shows how to generate a URL to " testnumber/1", I need to generate "testnumber/1/question/4".
For
generateURL('testnumber', array('testid'=>1, 'question'=>4))
to work as you want, your route must look like (example using annotations)
#Route("/testnumber/{testid}/question/{question}", name="testnumber")
If you don't define "testid" & "question" parameters in your route, they'll be added to the query string (appended at the end of the URL as GET paramaters)
generated_route?test_id=X&question=X
Find here more relevent examples.

IgnoreRoute with webservice - Exclude asmx URLs from routing

Im adding the filevistacontrol to my asp.net MVC web application.
I have a media.aspx page that is ignored in the routing with
routes.IgnoreRoute("media.aspx");
This works successfully and serves a standard webforms page.
Upon adding the filevistacontrol, I can't seem to ignore any calls the control makes to it's webservice.
Eg the following ignoreRoute still seems to get picked up by the MvcHandler.
routes.IgnoreRoute("FileVistaControl/filevista.asmx/GetLanguageFile/");
The exception thrown is:
'The RouteData must contain an item named 'controller' with a non-empty string value'
Thanks in advance.
Short answer:
routes.IgnoreRoute( "{*url}", new { url = #".*\.asmx(/.*)?" } );
Long answer:
If your service can be in any level of a path, none of these options will work for all possible .asmx services:
routes.IgnoreRoute("{resource}.asmx/{*pathInfo}");
routes.IgnoreRoute("{directory}/{resource}.asmx/{*pathInfo}");
By default, the parameters in a route pattern will match until they find a slash.
If the parameter starts with a star *, like pathInfo in those answers, it will match everything, including slashes.
So:
the first answer will only work for .asmx services in the root path, becasuse {resource} will not match slashes. (Would work for something like http://example.com/weather.asmx/forecast)
the second one will only work for .asmx services which are one level away from the root.{directory} will match the first segment of the path, and {resource} the name of the service. (Would work for something like http://example.com/services/weather.asmx/forecast)
None would work for http://example.com/services/weather/weather.asmx/forecast)
The solution is using another overload of the IgnoreRoute method which allows to specify constraints. Using this solution you can use a simple pattern which matches all the url, like this: {*url}. Then you only have to set a constraint which checks that this url refers to a .asmx service. This constraint can be expressed with a regex like this: .*\.asmx(/.*)?. This regex matches any string which ends with .asmx optionally followed by an slash and any number of characters after it.
So, the final answer is this:
routes.IgnoreRoute( "{*url}", new { url = #".*\.asmx(/.*)?" } );
I got it to work using this (a combo of other answers):
routes.IgnoreRoute("{directory}/{resource}.asmx/{*pathInfo}");
What happens when you use:
routes.IgnoreRoute("FileVistaControl/filevista.asmx");
If that doesn't work, try using the ASP.NET Routing Debugger to help you:
http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx
Try this:
routes.IgnoreRoute("{*filevista}", new { filevista = #"(.*/)?filevista.asmx(/.*)?" });
This is based on a Phil Haack recommendation stated here.
Have you tried:
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.asmx/{*pathInfo}");
It would help if you posted the source for your route configuration. I'm going to take a shot in the dark and say to make sure that your IgnoreRoute() calls are all at the top of your routing definition.
The way IgnoreRoute works is to create a route that matches the ignored route URL and constraints, and attaches a StopRoutingHandler as the RouteHandler. The UrlRoutingModule knows that a StopRoutingHandler means it shouldn't route the request.
As we know, the routes are matched in the order of which they are defined. So, if your {controller}/{action}/{id} route appears before your "FileVistaControl/filevista.asmx/GetLanguageFile/" route, then it will match the "{controller}/{action}/{id}" route.
I may be totally off base here, but it's hard to know without seeing your source. Hope this helps. And post source code! You'll get better answers.

How to get original url after HttpContext.RewritePath() has been called

I am working on a web app which makes use of a 3rd party HttpModule that performs url rewriting.
I want to know if there's any way to determine the original url later on in Application_BeginRequest event. For example...
Original url:
http://domain.com/products/cool-hat.aspx
Re-written url (from 3rd party httpmodule):
http://domain.com/products.aspx?productId=123
In the past I have written HttpModules that store the original url in HttpContext.Items but, this is a 3rd party app and I have no way of doing that.
Any ideas would be appreciated.
Try this:
string originalUrl = HttpContext.Current.Request.RawUrl;
The original URL is inside of this property.
I had the same problem, but I wanted the fully qualified URL (RawUrl gives you just the Path and Query part). So, to build on Josh's answer:
string originalUrlFull =
Page.Request.Url.GetLeftPart(System.UriPartial.Authority) +
Page.Request.RawUrl
I know this question was asked long time ago. But, this is what I use:
System.Uri originalUri = new System.Uri(Page.Request.Url, Page.Request.RawUrl)
Once you have the URI you can do a ToString() to get the string, or cal any of the methods/properties to get the parts.
Create a new HttpModule to serve as a wrapper around (inherits) the third party module and do whatever you want with it.
In your case, override the appropriate function (ProcessRequest?) and store the original url in HttpContext.Items, and then call the MyBase implementation. Should work fine.

What is the most efficient way to perform the reverse of Server.MapPath in an ASP.Net Application

I am building an MVC application in which I am reading a list of files from the file system and I want to pass the relative URL to that file to the view, preferably prefixed with "~/" so that whatever view is selected cab render the URL appropriately.
To do this, I need to enumerate the files in the file system and convert their physical paths back to relative URLs. There are a few algorithms I've experimented with, but I am concerned about efficiency and minimal string operations. Also, I believe there's nothing in the .Net Framework that can perform this operation, but is there something in the latest MVC release that can?
At the moment I don't know any built-in method to do it, but it's not difficult, I do it like this:
We need to get the Application root, and replace it in our new path with ~
We need to convert the backslashes to slashes
public string ReverseMapPath(string path)
{
string appPath = HttpContext.Current.Server.MapPath("~");
string res = string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/"));
return res;
}
Isn't this what UrlHelper.Content method does? http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content.aspx
I did some digging, trying to get the UrlHelper class to work outside of a controller, then I remembered a old trick to do the same thing within an aspx page:
string ResolveUrl(string pathWithTilde)
Hope this helps!
See:
https://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl(v=vs.110).aspx

Resources