How to retrieve site root url? - c#

I need to get the url of the site so that I render a user control on only the main page. I need to check for http://foo.com, http://www.foo.com, and foo.com. I am a bit stumped as to how check for all 3. I tried the following which does not work.
string domainName = Request.Url.Host.ToString();
if (domainName == "http://nomorecocktails.com" | Request.Url.Host.Contains("default.aspx"))
{ //code to push user control to page
Also tried
var url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/";
Any thoughts?

You need to check if the Request.Path property is equal to / or /Default.aspx or whatever your "main page" is. The domain name is completely irrelevant. What if I accessed your site via http://192.56.17.205/, and similarly, what if your server switched IP addresses? Your domain check would fail.
If you utilize the QueryString to display different content, you'll also need to check Request.QueryString.
Documentation for Request.Path:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.path.aspx
Documentation for Request.QueryString:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring.aspx

If you need the user control to only appear on the main page (I'm assuming you mean home page), then add the code to call the user control to the code behind of that file.
If this code is stored in the master page, then you can reference it like:
Master.FindControl("UserControlID");
If you are only using the one web form (ie. just Default.aspx), then you can check that no relevant query strings are included in the URL, and display only if this is the case:
if (Request.QueryString["q"] == null){
//user control code
}
However if you are using this technique then I would recommend using multiple web forms using master pages in the future to structure your application better.
The ASP.NET website has some good tutorials on how to do this:
http://www.asp.net/web-forms/tutorials/master-pages

Related

How to manipulate a url to access a parent directory

I have an asp.net web application that is being hosted on an internal network. In my testing environment of course it gets hosted out on localhost:01010/Views/page.aspx. now whenever I take it live the Url changes to server_name/folder 1/folder 2/views/page.aspx. what I am trying to do is get a new page to open up as server_name/folder 1/folder 2/Uploaded_Images/randomimage.png. Now I Can get the url, but as soon as I do a single ".Remove(url.lastindexof("/")+1)" it returns "server_name/folder 1/folder 2/Views". The I perform my second ".Remove(url.lastindexof("/")+1)"
and the it only returns "server_name/". I am ripping my hair out at this one and am hoping somewhere in the world a .net developer already has this built in. Appreciate all the help.
Also just to specify this is webforms and not mvc. also there is no ajax or page manipulation going on except for a response.write to open the new page.
You don't need the +1, this works:
var url = "server_name/folder 1/folder 2/views/page.aspx";
url = url.Remove(url.LastIndexOf("/"));
url = url.Remove(url.LastIndexOf("/"));
Or you could do it like this:
var parts = url.Split('/');
var newPath = string.Join("/", parts.Take(3));
I assume you are talking about URL's used as links to parts of your site and not physical paths on the file system.
In most cases, you should be able to use methods that construct paths on the fly. For example, in any of your .aspx files (or .aspx.cs files), you can use the ResolveUrl method, like this:
Some link
If there are any places where you need the full URL including the domain (like for email notifications or something like that) then what I have done is keep a static variable accessible to my whole application that gets set the first time Application_BeginRequest runs:
void Application_BeginRequest(object sender, EventArgs e) {
if (SiteRoot == null) {
SiteRoot = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
(VirtualPathUtility.ToAbsolute("~") == "/" ? "" : VirtualPathUtility.ToAbsolute("~"));
}
}
That will pull the full URL from the Request details (the URL that the user used to access your site), without any trailing slash.

MVC Redirect to another page

I have a controller which processes an uploaded file.
In that controller, I return the user to a SharePoint list depending on the successful parsing of that file. I am able to enter a direct URL, but I am opening this page in a form so I need to change the window.top.location instead of just window.location. I tried doing this a few ways such as returning a JavaScript result, but I received some browser warning messages I'd like to avoid.
I ended up making a partial razor view which grabs a parameter from the query string in order to determine which list it should go to. The function works fine, but the page is seemingly inactive when I return it using:
return Redirect("~/Parsing/ParsingRedirector?List=MasterDealer");
My page exists in the folder, but I get an error stating "The resource cannot be found. "
Any reason why that's happening? I admittedly don't have a full understanding of MVC or even close to it at this point.
Try this:
return RedirectToAction("ParsingRedirector", "Parsing", new { List = "MasterDealer"});
This may be of help:
http://www.dotnet-tricks.com/Tutorial/mvc/4XDc110313-return-View()-vs-return-RedirectToAction()-vs-return-Redirect()-vs-return-RedirectToRoute().html
Keep in mind that, per that article, in the case of Redirect "you have to specify the full URL to redirect."

How do I identify a user returning to my ASP.NET MVC site from elsewhere?

How can I determine if a user is hitting my site from elsewhere (i.e. from a new tab or another site)? I need to present a 'welcome back' message to returning users who are still logged in, but I don't want it appearing if they're just navigating within my site or, say, reloading the homepage.
I've considered using Onload/Onbeforeunload (or similar) to keep track of whether there is currently a view open, but this just adds complexity.
Can I assume that if Request.UrlReferrer doesn't contain my domain then it's a 'fresh' visit?
Try this,
if(Request.UrlReferrer != null && Request.UrlReferrer.Host != Request.Url.Host)
{
// User visit your page from another site/domain
}

Kentico: How to redirect based on document type field

I have a certain document type in Kentico that has a boolean field that when true i need the page to redirect to another URL (in this case a 404 page).
Where is the best place to do this?
and how do i access the kentico data context in code so that i can write code that pulls the document types field and redirects based on it (because currently trying to access Dataitem("MyFieldName") errors because Kentico doesn't use DataItem for data binding, even though Eval("MyFieldName") still works.
You can access Kentico context data via the CMSContext object.
<%
if ((bool)CMSContext.CurrentDocument.DataRow["MyFieldName"])
Response.Redirect("PageNotFound.aspx");
%>
If you only want to be able to redirect a page to another page. Kentico already have something built in, just go to the Page->Properties->Menu. In the menu actions section you can specify a URL for redirection.
Otherwise for requirement described you can get the boolean value by:
if(ValidationHelper.GetBoolean(
CMSContext.CurrentDocument.GetValue("MyFieldName"), false)))
{
Response.Redirect("/404.aspx");
}

Override ~ behaviour in controls

Quick backstory: I'm making a "framed" version of my site that has a different master page than normal (one suitable for iframing). It's accessed by mysite.com/Framed/whatever, instead of mysite.com/whatever. This is rewritten in IIS to mysite.com/whatever?framed=true. That works fine.
The issue I'm having is that all the links are relative using a ~ like ~/Server.aspx which works fine in the normal site. I need to override that so instead of producing ../Server.aspx (as it "should") it produces ../Framed/Server.aspx or Server.aspx.
Currently this means that the page goes back to it's normal view (mystite.com/whatever2) as soon as you click on a link, I want it to continue to stay in mysite.com/Framed/...
Don't you really want "../Server.aspx?framed=true" ? That might be easier to pull off
~ resolves to the root of the application, so you could create a virtual directory beneath your main site for your framed version called "Framed", so "~/" resolves to "/Framed/". Then instead of using a query string switch to select your master page, you can check for the presence of "/Framed/" in the raw request URI.

Categories