How to create a fully qualified hyperlink to a resource dynamically? - asp.net

In ASP.NET I'd like to create a link which points to a specific Uri and send this link in an email to a user, for instance something like http://www.BlaBla.com/CustomerPortal/Order/9876. I can create the second part of the Uri /CustomerPortal/Order/9876 dynamically in code-behind. My question is: How can I create the base Uri http://www.BlaBla.com without hardcoding it in my application? Basically I want to have something like:
http://localhost:1234/CustomerPortal/Order/9876 (on my development machine)
http://testserver/CustomerPortal/Order/9876 (on an internal test server)
http://www.BlaBla.com/CustomerPortal/Order/9876 (on the production server)
So is there a way to ask the server where the application is running: "Please tell me the base Uri of the application" ? Or any other way?
Thank you in advance!

Something like this:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath.TrimEnd('/')

You have to put a key in config, something somewhere, because when you think about your web application, it's not really tied to a URL. For example:
http://localhost:1234/
http://yourMachineName:1234/
http://yourMachineName.domain.com:1234/
http://127.0.0.1:1234/
These are just a few ways to get to the same site on localhost....which is it? The same problem exists in production, dozens of domains or IPs may point to the same web application, and it uses host headers or maybe nothing to distinguish it. The point is, when outside the context of a request, the site doesn't really know what URL it goes with, could be anything, there's just not a 1:1 relation there.
If you are in the context of a request when sending an email, then take a look at HttpRequest.Url, this is a Uri type, and you can see the available properties here.
You can do something like this:
var host = HttpContext.Current.Url.Host;
//generate your link using the host

What about to place it into the web.config
<configuration>
<appSettings>
<add key="SendingUrlBase" value="http://www.BlaBla.com"/>

Related

HttpHandler to download txt files (ASP.NET)?

Hey, I created a HttpHandler for downloading files from the server. It seems it is not handling anything...I put a breakpoint in the ProcessRequest, it never goes there.
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//download stuff and break point
}
}
It never stops there, as mentioned. I also registered it in the web.config.
<add verb="*" path="????" type="DownloadHandler" />
I am not sure about the path part of that entry. What do I have to enter there? I am downloading txt files, but the URL does not contain the filename, I somehow have to pass it to the handler. How would I do this? Session maybe?
Thanks
Have you read How to register Http Handlers? Are you using IIS 6 or 7?
The path part should contain a (partial) url, so if in your case you are using a static url without the filenames, you should put that there. You can end the url in the name of a non-existent resource and map that to path
e.g. the url is http://myserver.com/pages/downloadfiles
and the path="downloadfiles"
If you do POST, you can put the filename in a hidden field, and extract it in the handler. If you're using GET, I'm not sure, either cross-post the viewstate or put the filename in the session like you said.
Any reason why you can't put the filename in the url?
The path for a handler needs to be the path you are trying to handle - bit of a tautology I know but it's as simple as that. Whatever path on your site (real or much more likely virtual) you want to be handled by this handler.
Now unless the kind of file at the end of that path is normally handled by ASP.NET (e.g. .aspx, .asmx but not a .txt) ASP will never see the request in order for it to go through it's pipeline and end up at your handler. In that case you have to bind the extension type in IIS to ASP.NET.
As far as identifying what file the handler is supposed to respond with you could achieve this any number of ways - I would strongly recommend avoiding session or cookies or anything temporal and implicit. I would instead suggest using the querystring or form values, basically anything which will show up as a request header.
Fianlly, I have to ask why you're using a handler for this at all - .txt will serve just fine normally so what additional feature are you trying to implement here? There might well be a better way.

How do I get the host domain name in ASP .NET without using HttpContext.Current.Request?

I've got an ASP .Net application running on IIS7. I'm using the current url that the site is running under to set some static properties on a class in my application. To do this, I'm getting the domain name using this (insde the class's static constructor):
var host = HttpContext.Current.Request.Url.Host;
And it works fine on my dev machine (windows XP / Cassini). However, when I deploy to IIS7, I get an exception: "Request is not available in this context".
I'm guessing this is because I'm using this code in the static constructor of an object, which is getting executed in IIS before any requests come in; and Cassini doesn't trigger the static constructor until a request happens. Now, I didn't originally like the idea of pulling the domain name from the Request for this very reason, but it was the only place I found it =)
So, does anyone know of another place that I can get the host domain name? I'm assuming that ASP .Net has got to be aware of it at some level independent of HttpRequests, I just don't know how to access it.
The reason that the domain is in the request is...that's what's being asked for. For example these are a few stackexchange sites from http://www.stackexchangesites.com/:
http://community.ecoanswers.com
http://www.appqanda.com
http://www.irosetta.com/
If you ping them, you'll see they all point to the same IP/Web Server and be served by the same app (or multiple apps in this case, but the example holds if it was one big one)...but the application doesn't know which one until a host header comes in with the request asking the server for that site. Each request may be to a different domain...so the application doesn't know it.
If however it doesn't change, you could store it as an appSetting in the web.config.
Use global.asax or write a HttpModule and subscribe to start request events. You will have the request passed into your event handler.
Use this instead:
HttpRuntime.AppDomainAppVirtualPath
Or if you want the physical path:
HttpRuntime.AppDomainAppPath
For further reading:
http://weblogs.asp.net/reganschroder/archive/2008/07/25/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-application-start.aspx

Create dedicated URL for each user (ASP .net)

I would like to allow my users to have their own dedicated URL, for example if my URL is www.XYZ.com, my users will have www.NAME.XYZ.com OR www.XYZ.com/NAME.
At the moment you can see their page by going to www.XYZcom/Member.aspx?userID="012345"
Now I would like to somehow map the URL to the currect system.
I have no idea whatwhat I need to do, I have seem many websites that have done this, so I hope that it would be possible for me to do the same in ASP .net.
Thank you in Advance.
Cheers
If your domain name DNS record is pointing to the IP address of the site, you should be able to access the site using anything.XYZ.com.
When you create a users account, you need to asign them a unique subdomain name and then detect this when users get to the site using their domain name (see the code below)
/// <summary>
/// Gets the Current SubDomain
/// </summary>
/// <returns></returns>
public static string GetSubDomain()
{
string subDomain = String.Empty;
if (HttpContext.Current.Request.Url.HostNameType == UriHostNameType.Dns)
{
subDomain = Regex.Replace(HttpContext.Current.Request.Url.Host, "((.*)(\\..*){2})|(.*)", "$2");
}
if (subDomain.Length == 0)
{
subDomain = "www";
}
return subDomain;
}
If you need to do this with IIS and ASP.NET i think this method will work:
Use a DNS-host that will allow you do register wildcard-domains. That way you can register ****.xyz.com*** to point to your server.
Now comes the part you may not like; for this to work on IIS you will need to set up your site as "default web site". That way, all requests will come to your site, even if the subdomain is not in the list of headers for that site. This will not work if your site is hosted on a shared webhost.
Use Marks method to detect what domain the user has typed in.
HI,
You can use URL Rewriting in your application. Using this feature simply you can redirect URLs like : www.XYZ.com/012345 to the page: www.XYZ.com/Member.aspx?userID="012345". You can download URL Rewriter sample from microsoft website. after you add URLRewriter.dll reference to your website. After you add the following lines to your web.config file in your website:
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/([a-z]+)-([a-z]+)\.html</LookFor>
<SendTo>~/Contact.aspx?FirstName=$1&LastName=$2</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>
The above code redirects(using URLRewriter library) URLs like www.mydomain.com/name-family.html to www.mydomain.com/Contact.aspx?FirstName=name&LastName=family you can change this to suite your needs. Content of LookFor tag are some regular expression for my case, you should write your own regular expression.
You can view the article and download the source code here at MSDN.

Use the ASP.NET request user for Log4net log entries

My ASP.NET site is using Integrated Authentication with impersonation turned off. I have added a "%username" to my "conversionPattern" in the web.config to add the user name to each logging entry. However this will use the application pool identity's user name, and not the current visiting user's name.
Any ideas on how best to do this? Do I have to write a custom appender? I don't mind any minor performance penalties as this is a small intranet site. Thanks!
There's built in ASP.NET pattern converters in recent versions of log4net:
%aspnet-request{REMOTE_ADDR} and %aspnet-request{AUTH_USER}
https://stackoverflow.com/a/7788792/74585
You can also access the contents of
aspnet-cache
aspnet-context
aspnet-session
https://logging.apache.org/log4net/log4net-1.2.13/release/sdk/log4net.Layout.PatternLayout.html
An alternative (and easier) solution you may want to take a look at is to use the ThreadContext class (formerly implemented as the MDC and NDC classes). You could have something like this inside an HttpModule (before the request arrives at your page) or anywhere else before you log your first message:
ThreadContext.Properties["user"] = username;
And then include the following in your conversionPattern:
%property{user}

URLs for e-mailing in ASP.NET MVC

How would I generate a proper URL for an MVC application to be included in an e-mail?
This is for my registration system which is separate from my controller/action. Basically, I want to send an email verification to fire an Action on a Controller. I don't want to hardcode the URL in, I would want something like the Url property on the Views.
In your Controller, the UrlHelper is just called "Url" - so:
void Index() {
string s = this.Url.Action("Index", "Controller");
}
The "this" is unnecessary, but it tells you where this Url variable comes from
I used:
Html.BuildUrlFromExpression<AccountController>(c=>c.Confirm(Model.confirmedGUID.Value))
It is part of the HTMLHelper (I think in the MVC Futures) so you may have to pass an instance of the HTMLHelper to your service layer, not sure. I use this directly in my view which renders to an email. That gives you the absolute URL and then I store the domain (http://www.mysite.com) in the config file and append it before the URL.
You should probably make the URL part of the configuration of your application.
I know you can do stuff with e.g. the Server property on your web application, but the application will never know if its IP or domain name is reachable from the outside as it might be hidden behind a proxy or a load balancer.
If I'm reading the question correctly, you need to controller/action outside the MVC code. If so, you will need to simply configure the URL in Application Configuration or some such place, unless you have access to the controller classes and use reflection to get the names.

Resources