user1372494
user1372494

Reputation:

An alternative approach to URL Rewriting and Postbacks with Global.asax?

I've been having an issue with URL Rewriting and Postbacks.

Edit: Currently using IIS 7 and the URL Rewrite module.

Basically after a Postback, my URL Rewriting completely messes up and added some duplicated and unnecessary field value pairs to my query string. Considering I was parsing the URL in my code, this broke an already working page after a Postback is raised.

From what I saw many people before me had the same issue and pretty much all of them have fixed it with modifying the Form Action on PageLoad, like so:

protected void Page_Load(object sender, EventArgs e)
    {
        form1.Action = Request.RawUrl;

        //Some other interesting things.
    }

Important: This did the trick, it works.

However, although my developing experience is literally less than a month, I've been trying so far to look for more elegant solutions to my problems. I've been hinted that there might be a better alternative that involves editing the Global.asax in order to have the same results on a more "global" level.

This should, in my opinion, make it more efficient overall as the trick will be done before any other page is called.

So my actual question is:

How can I achieve the same by editing the Global.asax file instead of modifying the Form Action on my MasterPage loading event? If you have an even more elegant solution I would appreciate that you include it as well.

Considering this is my first question, I hope I've been constructive enough.

Upvotes: 0

Views: 2008

Answers (2)

Kevin Main
Kevin Main

Reputation: 2344

If you are unable to change the rewrite method then I can think of two approaches which may be better than what you have.

1) Create a base page and rewrite the action in it - all pages should then inherit from the new base page. This keeps the code in one place and you do not have to write in every page.

2) Inherit from the default form control and stop it rendering the action property altogether, it will then postback to the rewritten URL instead. Then replace all your form instances with your new control. You can see what I mean about half way down this article http://msdn.microsoft.com/library/ms972974

Edit

3) Scott Gu posted a solution to this problem (in this article http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx) which is much cleaner and does not involve changing any code by using Control Adapters.

Upvotes: 1

levi
levi

Reputation: 3511

There is one more way through iis:

IIS URL Rewriter and explained

I advice you to calculate root(in master page property if exists master) like this:

Root = "http://" + Request.Url.Host + Request.ApplicationPath;
Root += (Root.EndsWith("/") ? "" : "/");

and than paste it in .aspx using this directive:

<%=Root %>

Upvotes: 0

Related Questions