Is it possible to get the URL of the next page when leaving the current page in C#?
On my current page I would like to capture the url of the next page before the next page loads. I'm not sure where to start for this...or in which method on my page I would place this logic (such as page_load, buttonClick etc.)
I don't think that it's possible to "capture the url of the next page", but you can get the current request as soon as possible. Use Global.asax therefore:
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = base.Context;
HttpResponse response = context.Response;
HttpRequest request = context.Request;
var url = request.RawUrl;
// and many other properties ...
}
}
Assuming you're doing paging through query strings and your current page is:
url.com/default.aspx?page=1
Then getting the next page URL would just be incrementing the page query string, so:
if (!String.IsNullOrempty(Request.QueryString["page"]) {
int nextPageNumber = int.Parse(Request.QueryString["page"] + 1;
string nextPageUrl = String.Format("url.com/default.aspx?page={0}, nextPageNumber);
}
Ideally you would use UriBuilder to reconstruct the domain and not hard code it as I have in the String.Format method. I did this just for brevity.
CodeProject has a project for saving change on close or exiting page which might be helpful to you.
Related
public static class HttpRequestHelper
{
public static string RequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
}
I plan to call this from ActionFilters to log incoming requests. Of course there could be multiple simultaneous requests.
Is this approach ok?
Is your question from the perspective of concurrency or ASP.NET Web API in general? Every request has its own context and you are okay with multiple requests going on in parallel. But here are two things for you to look at.
(1) Since you are using HttpContext, you are locking yourself to web hosting (IIS), which in many cases should be okay. But I would like you to be aware of this.
(2) Your code HttpRequestHelper.RequestBody() will work when called from an action filter, as you mentioned. However, if you try to call this from other places, say a message handler, this will not work. When I say this will not work, parameter binding that binds request body to action method parameter will not work. You will need to seek to the beginning once you are done. The reason it works from action filter is that binding would have already happened by the time action filter runs in the pipeline. This is another thing you might need to be aware of.
I've needed use InputStream of Http Request. I have a WebApp and IOS App that navigates to a aspx page, if the url request contains some parameters i read the information in database and if i not find any parameters in url request i read the request body and i work fine !
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(Request.QueryString["AdHoc"]) == false)
{
string v_AdHocParam = Request.QueryString["AdHoc"];
string [] v_ListParam = v_AdHocParam.Split(new char[] {','});
if (v_ListParam.Length < 2)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(WS_DemandeIntervention));
WS_DemandeIntervention response = (WS_DemandeIntervention)jsonSerializer.ReadObject(Request.InputStream);
....
}
if (string.IsNullOrEmpty(Request.QueryString["IdBonDeCommande"])==false)
{
....
I have 2 different system, lets say SystemA and SystemB.
In SystemB, there is page, say calculate.aspx, where it receive certain parameter and will perform some calculation. This page doesn't display and info, and only serves to execute the code behind.
Now i have a page in SystemA, lets say execute.aspx, that will need to call calculate.aspx in SystemB to run the desired calculation. I cannot use redirect, since that will redirect me to the calculation.aspx page on SystemB.
I had tried using HttpWebRequest but it doesn't call to the page. The code is as below:
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(nUrl + '?' + fn);
myRequest.Method = "GET";
WebResponse response = myRequest.GetResponse();
Does anyone know what is the correct way of doing it? Thanks.
EDIT
Manage to get it done after changing my codes to above. Thank you all.
You can either use a web service which would be the preferred way or use AJAX to send data to the page and get result in response.
I am probably missing something obvious here, but I'm puzzled by the whole part about the data and content which I'm not used to see in a GET Request.
You should, at your choice :
convert your request to POST
remove the part concerning the data
try this
namespace SampleService // this is service
{
public class Service1 : IService1
{
public string GetMessage()
{
return "Hello World";
}
public string GetAddress()
{
return "123 New Street, New York, NY 12345";
}
}
}
protected void Page_Load(object sender, EventArgs e) // calling the service
{
using (ServiceClient<IService1> ServiceClient =
new ServiceClient<IService1>("BasicHttpBinding_IService1"))
{
this.Label1.Text = ServiceClient.Proxy.GetMessage();
//once you have done the build inteli sense
//will automatically gets the new function
this.Label2.Text = ServiceClient.Proxy.GetAddress();
}
}
refer this link
http://www.codeproject.com/Articles/412363/How-to-Use-a-WCF-Service-without-Adding-a-Service
You can create a WebMethod in your application then you call this WebMethod from any other application, you can return Json serializable or XML data from this WebMethod
I have a page that if you don't have the cookie i want it redirects you to the page the cookie is created. Basically if you didn't tell me you are old enough you gotta redirect to a page and give me your age. Long story short if i get redirected to this page where i am asking for you age and the end user doesn't decide to give me there age and click on that same page or another page. My code is adding onto the existing string.
protected void Page_Load(object sender, EventArgs e)
{
string referrer = Request.UrlReferrer.ToString();
if (Request.Cookies["Age"] == null)
Response.Redirect("/AgeRestricted/?ReturnUrl=" + referrer);
}
if I call this page to load multiple times my URLS can get really ugly.
http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/
it is like it is concatenating onto the existing. Is there a way for me to prevent this?
I basically want to have it so that i only have 1 param in my ReturnUrl QueryString and so that it won't duplicated if that already has a value.
You can do this by using the Uri class to obtain only the parts of the referrer without the query string. For example:
if (Request.Cookies["Age"] == null)
{
string referrer = Request.UrlReferrer.GetLeftPart(UriPartial.Path);
Response.Redirect(referrer);
}
For more information on GetLeftPath, see: http://msdn.microsoft.com/en-us/library/system.uri.getleftpart.aspx
Here is the code that fixed the problem. Don't know why my last answer was deleted.
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if (Request.Cookies["Age"] == null)
Response.Redirect("/AgeRestricted/?ReturnUrl=" + url);
I have some proof concept code for a HTTP module. The code checks to see if a cookie exists, if so it retrieves a value, if the cookie does not exist it creates it and sets the value.
Once this is done I write to the screen to see what action has been taken (all nice and simple). So on the first request the cookie is created; subsequent requests retrieve the value from the cookie.
When I test this in a normal asp.net web site everything works correctly – yay! However as soon as I transfer it to SharePoint something weird happens, the cookie is never saved - that is the code always branches into creating the cookie and never takes the branch to retrieve the value - regardless of page refreshes or secondary requests.
Heres the code...
public class SwithcMasterPage : IHttpModule
{
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
// register handler
context.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}
void PreRequestHandlerExecute(object sender, EventArgs e)
{
string outputText = string.Empty;
HttpCookie cookie = null;
string cookieName = "MPSetting";
cookie = HttpContext.Current.Request.Cookies[cookieName];
if (cookie == null)
{
// cookie doesn't exist, create
HttpCookie ck = new HttpCookie(cookieName);
ck.Value = GetCorrectMasterPage();
ck.Expires = DateTime.Now.AddMinutes(5);
HttpContext.Current.Response.Cookies.Add(ck);
outputText = "storing master page setting in cookie.";
}
else
{
// get the master page from cookie
outputText = "retrieving master page setting from cookie.";
}
HttpContext.Current.Response.Write(outputText + "<br/>");
}
private string GetCorrectMasterPage()
{
// logic goes here to get the correct master page
return "/_catalogs/masterpage/BlackBand.master";
}
This turned out to be the authentication of the web app. To work correctly you must use a FQDM that has been configured for Forms Authentication.
You can use Fiddler or FireBug (on FireFox) to inspect response to see if your cookie is being sent. If not then perhaps you can try your logic in PostRequestHandlerExecute. This is assuming that Sharepoint or some other piece of code is tinkering with response cookies. This way, you can be the last one adding the cookie.
i am trying to remove default.aspx from any request that might have it.
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
string url = context.Request.Url.ToString();
// remove default.aspx
if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
{
url = url.Substring(0, url.Length - 12);
context.Response.Redirect(url);
}
}
gives an error:
**too many redirects occurred trying to open...**
what can i change to make it work?
thnx
k got it.
instead of using:
string url = context.Request.Url.ToString();
i tried:
string url = context.Request.RawUrl.ToString();
and that WORKS! together with what you guys said :)
I think that if you put the redirect inside the if you don't have to deal with infinite redirects.
You are endlessly redirecting.
Each time the following line executes the Application_BeginRequest event is fired again.
context.Response.Redirect(url);
Put the redirect inside the if statement like this.
if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
{
url = url.Substring(0, url.Length - 12);
context.Response.Redirect(url);
}