Asp.net - HttpContext.Current.Request.Url.AbsolutePath Return An Empty String?
Oct 6, 2010
When user requests http://localhost/WebApp1/Default.aspx, txtApplicationPath.Text should be assigned "/WebApp1", while txtAbsolutePath.Text should be assigned "http://localhost/WebApp1/Default.aspx", but instead both textboxes display empty strings.
I have various web pages that need to build up a URL to display or place it in an emitted email message. The code I inherited had this value for the name of the webserver in a Public Const in a Public Class called FixedConstants. For example:
Public Const cdServerName As String = "WEBSERVERNAME"
Trying to improve on this, I wrote this:
Public Class UIFunction Public Shared myhttpcontext As HttpContext Public Shared Function cdWebServer() As String Dim s As New StringBuilder("http://") Dim h As String h = String.Empty Try h = Current.Request.ServerVariables("REMOTE_HOST").ToString() Catch ex As Exception Dim m As String m = ex.Message.ToString() 'Ignore this should-not-occur thingy End Try If h = String.Empty Then h = "SomeWebServer" End If s.Append(h) s.Append("/") Return s.ToString() End Function
I've tried different things while debugging such as HttpContext.Current.Request.UserHostName and I always get an empty string which pumps out my default string "SomeWebServer". I know Request.UserHostName or Request.ServerVariables("REMOTE_HOST") works when invoked from a page but why does this return empty when invoked from a called method of a class file (i.e. UIFunction.vb)?
Why does HttpContext.Current.Request.Url.Host return a different URL than the URL used in the Web browser? For example, when entering "www.someurl.com" in the browser, the HttpContext.Current.Request.Url.Host variable is equal to "www.someotherurl.com".
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.
I have IIS on S2k8 and a website with Windows Authentication only.
I can easily reproduce the following scenario, where HttpContext.Current.Request.LogonUserIdentity.Name has a bad value:
Login to website using FireFox, using an Active Directory account "user" (I could use IE to reproduce the same, but it's a few extra steps)Display <%=System.Web.HttpContext.Current.Request.LogonUserIdentity.Name%> on the pageIt shows "DOMAINuser", which is correctI go into Active Directory and rename the account to be "userX" instead of "user" (both SAMAccountName & UPN)Restart FireFoxLogin to website using "userX" accountThe page still shows "DOMAINuser", instead of the expected "DOMAINuserX"
It seems almost as if IIS has cached the old username and it's not showing me the new one, even though I explicitly enter it in the login prompt.
In an asynchronous process, I need to get the name of the domain/server the web application is running on. But in that situation HttpContext.Current is not available, so I cant use HttpContext.Current.Request.ServerVariables("SERVER_NAME").
I was/am struggling with security for my first MVC applicaiton. It worked out great for me, but not for my users. I wanted to use Windows Authentication (and I seem to have that working). But when I was still trying to implement it, I was on one of our users computers where they were logged in. I navigated to the main Index page and used the supplied MVC login link and *MY* credentials. So now every time that user navigates to that page, it logs her in as me. We are using IE8, I have deleted all the cookies, passwords, forms information I can fine through Tools|Internet Options|Tool|Content|AutoComplete.
Is there room for issue in the following code in terms of multiple users of the same web application? I mean, I know that a purely static string will be shared across all sessions for a single ASP.NET application, but since this explicitly refers to the Current.Session, even though it is static it seems like it would always refer to the session instance of the "current user." But an error is happening that could be explained by everyone sharing the current value of Mode and thus the most recent change overwriting everyone else's mode value. (As a background: This string is in a Helpers class that is used throughout the application. I do not want to make references to Session["Mode"] throughout the application and do not want to have to pass Session["Mode"] in every method call from an aspx.cs page.)
public static string Mode { get { var value = HttpContext.Current.Session["Mode"]; return (value ?? string.Empty).ToString(); } set { HttpContext.Current.Session["Mode"] = value; } }
I have one IIS entry with AppPool integrated mode. There are 5 or more host headers assigned. The application pulls data based on the host name from Request.Url.Host. When I have 2 or more sites open at the same time the value of the Request.Url.Host is the same across all the sites. About every 30 seconds it resets itself to the correct value from the last request and shows that value on the other sites. So ultimately the sites are loading the same data. The value in the HOST server variable is incorrect as well.
We're migrating an application to use IIS7 integrated mode. In library code that is designed to work either within the context of an HTTP request or not, we commonly have code like this:
if (HttpContext.Current != null && HttpContext.Current.Request != null) { // do something with HttpContext.Current.Request } else { // do equivalent thing without HttpContext.. }
But in IIS7 integrated mode the check for HttpContext.Current.Request throws an exception whenever this code is called from Application_Start.
System.Web.HttpException: Request is not available in this context
How can I detect whether the request is really available without wrapping these calls in an exception handler and taking action based on whether an exception is generated or not.
Looking at HttpContext in Reflector I see it has an internal bool HideRequestResponse field but it's internal so I can only get to it with reflection and that's fragile. Is there a more official/approved way to determine if it's ok to call HttpContext.Request?
This blog post about the subject says not to use HttpContext, but how, in generic library code, can you determine if it's ok to use HttpContext?
I'm using the work-around mentioned there which is to use Application_BeginRequest and an initialized field to only initialize once as part of BeginRequest, but that has to be done in every calling application whereas I'd prefer to make the library code more robust and handle this situation regardless of where it's called from.
I have a page that lists products from a table based on the querystring. So if I say foo.aspx?fam=1 all the products from family 1 will be listed. How can I make my code list all the values if query string is empty? My SQL command would have to be different...can't really see how I can do this.
I have created a web services (WCF) and i have a webmethod that return a string that string is a HTTPCONTEXT.USER.IDENTITY.USER unfortunately it does not return any value.
I have a requirement to build a simple ASP.NET web page which sends some parameters to a web service, and then displays the string which was returned. I'm a complete .NET newby and the only examples I can find seem really really complex. I just need something mega simple, but which an handle parameters being sent to the web service. Can anyone point me in the direction of a simple bit of C# which will do this with no frills or fuss?
I have a web app where I really needed to get the Page.Request.Url.AbsolutePath of the pages.
so My see my function below.
[code]....
Is always returning " " I changed the function to return s in instead of Path and I commented out s = s.Substring(s.LastIndexOf("/") + 1) this line as well. But I am getting only " "
One thing I have to specify is
When I compile the site I get [URL] and I have to click on some sub categories which makes the site url
I have a static class with serveral static methods. In these methods, I'm trying to access the current thread's context using HttpContext.Current. For example:
var userName = HttpContext.Current.User.Identity.Name;
However, when I do that, I receive a NullReferenceException, the infamous "Object reference not set to an instance of an object."
i'm using an example in which i can fake the session.It's for use in a unittest of a mvc controller.In the test i create a controller and then i do this:
FakeHttpContext httpctx = new FakeHttpContext(null,null,null,null,mSessionItems ); ControllerContext ctx2 = new ControllerContext(httpctx,new RouteData(), target);
here mSessionItems is my session and target is my instance of a controller,and indeed, when i'm in a controller reading this.ControllerContext.HttpContext.Session, i have a session, great!but.... i also read the session outside the controller, and there i use HttpContext.Current.Session, and that is null (or actualy, the HttpContext.Current is null).
I have been experimenting with code that will clear all of the cookies in an HttpContext.Response.Initially, I used this:
DateTime cookieExpires = DateTime.Now.AddDays(-1); for (int i = 0; i < HttpContext.Request.Cookies.Count; i++) { HttpContext.Response.Cookies.Add( new HttpCookie(HttpContext.Request.Cookies[i].Name, null) { Expires = cookieExpires }); }
this will error with an OutOfMemoryException because the for loop never exits - each time you add a cookie to the Response, it also gets added to the `Request.
Do these objects behave differently inside global.asax/global.asax.vb and default.aspx/default.aspx.vb.
Edit 2
OK I'll try to be specific this time. Which of the following should I use:
' File: global.asax Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs) If Request.Url.Port = 80 Then 'If HttpContext.Current.Request.Url.Port = 80 Then
As per title. I want to be able to save some data in a cache object but this object must be available to all users/sessions and can expire.What is the best method to achieve this in a asp.net web app?
I have some code that works fine when I need to delete some image files from a directory on my web server:
Dim ImageURL As String = dsImages.Tables(0).Rows(iImgRow).Item("ImageURL") Dim physicalName = Server.MapPath(ImageURL) oUpload.DeleteFileFromServer(physicalName, iAdid, iImgID)
.but I am running into a problem when a maintenance task running in a separate thread at set intervals determines that files like the above need to be deleted:
Dim ImageURL As String = dsImage.Tables(0).Rows(i - 1).Item("ImageURL") Dim iImgID As Integer = dsImage.Tables(0).Rows(i - 1).Item("ImageId") Dim physicalName As String = HttpContext.Current.Server.MapPath(ImageURL) oUpload.DeleteFileFromServer(physicalName, iAdID, iImgID)
In this latter case, HttpContext.Current.Server.MapPath(ImageURL) has a value of Nothing.Is there a way to get the full path for this case?