Basically, I need to know the answer to this question in asp.net/C#:
source of REQUEST
I would like one of my pages to know which page directed the user to this specific page. I've tried going through intellisense on a few different Page properties, but couldn't find it. Any help?
Sounds like your looking for Request.UrlReferrer
Documentation: HttpRequest.UrlReferrer
The request can be attained off the page:
Page.Request
If a Page instance is not available, you can get it from the current context using:
HttpContext.Current.Request
You can look at Request.ServerVariables("HTTP_REFERER") or Request.ServerVariables("URL").
Or you can use the Request object this way:
Request.Url.ToString() gives you the full path of the calling page.
If you call this in the Immediate Window without the ToString, you can see lots of information:
Request.UrlReferrer.ToString()
You're looking for the Request.UrlReferrer property.
I think you want Request.ServerVariables["HTTP_REFERER"];
EDIT:
Use #SLaks answer
We can get to know the referral Url from UrlReferrer property.
It's easy to handle in the global.asax file.
protected void Session_Start()
{
var SourceURL = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
Now we can store this value in session or somewhere and do what ever operation we would like.
Related
I'm in the code behind of a generic http handler (.ashx) and I'd like to get a reference to the instance of the calling .aspx page, so I can call some methods/get some properties of it. I can easily call static methods of the page, but I'm not able to get the actual object instance.
Is there a way, without resorting to services/webmethods/whatnot? Thanks!
EDIT:
I call the ashx from the JS inside the aspx page
$.ajax({
url: "handler.ashx",
context: "my content"
}).done(function() {
alert("Done");
});
Then I update an asp:Label with the result of it.
I've found a way to do it anyway (you can do it via JQuery from JS for instance), but now I'm curious if you can do it from the code behind simply calling some pageInstance.setMyLabel(ashxResult) or something like this.
There is no direct way to modify the contents of your calling .aspx-page via server-side code.
You should (like you mention yourself) process the results of the call to your .ashx-handler with javascript.
If you would like to use some results 'serverside' I think the only option is that you write some data to the session-object during the processing of the .ashx-handler.
On the next postback of the .aspx-page you could use that data to accomplish some change. If you would like to do that, please refer to this question also:
How to access Session in .ashx file?
The instance of the page class only exists for as long as it takes to process the request and send the response back to the client. By the time the Javascript code executes and makes a request to the ashx file, the page instance has been destroyed.
ASP.NET Page Life Cycle Overview | Microsoft Docs
I've a domain name called mywebsite.com but I prefer users to access to my website through the www subdomain.
How can I achieve a verification and redirection in asp.net mvc3 easily?
When I was using php I did something like that :
if($_SERVER['SERVER_NAME'] != "www.mywebsite.com")
header('Location: www.mywebsite.com');
I'd like to find a similar way to achieve this kind of redirection in asp.net (C#) (I'd prefer not to set a 301 redirection but just a soft redirection like the one I was using in PHP).
I know I could do a verification in each of my controllers action methods and the redirect the user if he is not on the subdomain www.mywebsite.com but I'd prefer to write once the verification and the redirection and I can't find where :/
Thanks a lot !
You could use:
Request.Url.ToString()
This will return the URL , then you can quickly check if it contains 'www.' and redirect if true. However I would suggest that your handle this in the URL rewrite in IIS.
Follow the guide here: http://www.dotnetexpertguide.com/2011/08/iis-7-redirect-domaincom-to.html this is for making domain.com go to www.domain.com, but it works the same way for the opposite.
you could try something like this
if(!Request.Url.Host.Equals("www.mywebsite.com"))
{
Response.Redirect("website");
}
If you are looking to just add/append header information, then use Response.AppendHeader().
The Request.Url.ToString() property can be checked for the url you are looking for as per Ryan's answer.
Actually, the original question asks specifically for a 'soft' redirection (201 or 202) instead of a Moved Permanently/Found (301/302), so i think that instead of Response.Redirect the conditional line should be:
if(!Request.Url.Host.Equals("www.mywebsite.com"))
{
HttpContext.Current.Response.Headers.Add("Location", "www.mywebsite.com");
}
EDIT: I believe the status may also be set directly, used in conjunction with Response.Redirect:
if(!Request.Url.Host.Equals("www.mywebsite.com"))
{
HttpContext.Current.Response.Redirect("www.mywebsite.com");
HttpContext.Current.Response.Status = "201 Created";
}
If I am not totally missing something here, can't you just setup the host-header in the IIS settings for the site to include both www.domain.com as well as domain.com?
I have web service with 40 different web methods.
Can I get in my web service the Method that the request sent from using HttpContext?
I need it because I have abstract general command that all the methods activate and I have access only to HttpContext.
Thanks!
If I understand correct your question you can use PathInfo property of the HttpRequest:
string methodName = HttpContext.Current.Request.PathInfo;
The string methodName will be the method name with the slash prefix (/): "/MyWebMethod".
You probably need:
HttpContext.Current
But be sure you've the ASPX compatibility mode turned on, otherwise you'll not be able to access that property
You can also save the name of the function into the Items array like this:
void myServiceMethod()
{
HttpContext.Current.Items["MethodName"] = "myServiceMethod";
// ...
// here comes your method implementation
}
and then you can anywhere read the HttpContext.Current.Items["MethodName"]
colection HttpContext.Current.Items is valid always only for current request, so you can use it as a storage for any request related information.
When the request is responded, it's garbage.
How can I clear browser cache only on logout, sure I can use the below:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
But this particular page which is a shopping bag page is accessible by both login and non-login users. How can I set it in such a way whereby the login user is able to access this page without clearing the browser cache but Only clears it when he/she logs out so that another user will not be able to access the history contents.
I have tried the solutions here:
http://www.codeproject.com/Tips/135121/Browser-back-button-issue-after-logout
made some changes but still couldn't figure out how to deal with this issue.
I also cleared my session on logout as below but I understand the browser cache will still stay.
FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect("~/");
Please advice. Thanks.
I am not a c# expert, but I am pretty sure what you have above only tells the browser to not cache the page you are on. There is no way to tell the browser to clear cache on any page. This would be a problem if there was such a way. Sounds like the solution you need is to not cache any page at all, regardless of logging out or not.
Perhaps you are getting muddled with the difference between server and client cache?
If you set output cache on your aspx page, that's server-side cache, and you have a scenario where .NET can decide whether to send pre-cached content or not, and still apply ACL rules.
If you set cache requirements on the HTTP you return using Response.Cache, that's client-side caching. Once the browser obeys the cache rules you send here, the only opportunity you will have to retract your cache rules is the next time the browser requests the page. If you set the cache to expire tomorrow, that's the next chance you'll get to amend the caching. Assuming the browser is obeying you, by the way, of which there is no guarantee.
In short, dynamic pages should not attempt to set client-side caching if you want them to stay dynamic. In fact you should actively use techniques such as the ones you mentioned to suppress Caching on those pages at all times.
Client-side caching should really only be used to assist with performance and bandwidth on the static parts of your site.
I am trying to solve a similar problem myself. This is just speculation, but if i could track a user specific header in my requests I was going to try using
HttpContext.Current.Response.Cache.VaryByHeaders["login"] = true;
in the global.asax
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg == "login")
{
return User().Name;
}
return base.GetVaryByCustomString(context, arg);
}
There is a way to do it. If you are caching a page, you can add a vary parameter. For Example
[OutputCache(Duration = 60, Location = System.Web.UI.OutputCacheLocation.Client, VaryByParam = "random")]
[CompressFilter]
public ActionResult Page(PageModel model)
{
...
}
In the example above, if I pass a random variable like the ticks of the current datetime object, that will prevent the cache.
I am currently trying to add a variable to the url using Server.Transfer. I need to use Server.Transfer as I need to keep form post data which is why I can't use Response.Redirect.
I am using Server.Transfer("add_account.aspx?error=userNotFound"); but the variable is not being added to the URL.
Thanks for your help.
Usually with Server.Transfer, we use context to pass data around:
Context.Items["error"] = "UserNotFound";
Server.Transfer("add_account.aspx");
This is a state container like Session and Application, but it only persists for the current request and then goes away.