Correct way to use Response.Redirect

2019-02-26 10:11发布

问题:

I'm having a an issue with Response.Redirect and despite reading plenty of posts, I haven't been able to resolve my particular issue.

The site I'm working on integrates with a third party via a webservice. The web service returns a result as expected, after which we do some housekeeping stuff, then redirect to a third party supplied url.

Here's what happens:

If we get a specific response back, we want to redirect to an affiliated site via a link provided in the response

  1. We make a request and receive a response
  2. We update the database SQL
  3. We send an email using System.Net Send

After the above, we want to redirect;

Response.Redirect(resp.RedirectUrl, false);
Context.ApplicationInstance.CompleteRequest();

Despite using what seems to be the correct approach, my third party informs me that we are getting a high percentage of failed redirects. Higher in the code tree, there's plenty of error catching, so when it gets to this point it should be a case of simply redirecting.

I know that this might not all be at our end, and have requested some pattern data to establish 'who' and 'when' it's happening with.

In the meantime, I'm trying to ensure that our side is as robust as possible, so I have a few questions.

  1. Is there anything fundamentally wrong with the above approach?
  2. Is the a better approach that could be used?
  3. Is there anything I could/should be testing

Thanks in advance.

回答1:

using this code

Response.Redirect(resp.RedirectUrl, false);
Context.ApplicationInstance.CompleteRequest();

you let your site run and other code (the rest on the lines and the rest on the life cycle events of the page ) that is not probably tested (because you believe that is not run and redirect) or may have some nulls and there you get exceptions - on the code that runs before the actual redirect.

Try to use that code, that stop further execution of your program

Response.Redirect(resp.RedirectUrl, false);
return;

with that you get an ThreadAbortException exception but you need to stop further run of your program with a controlled stop.

relative Redirect to a page with endResponse to true VS CompleteRequest and security thread



回答2:

As the Target URL is received from the third party, after saving them in the database. you can use 'Sever.Transfer' instead of 'Response.Redirect'.

Response.Redirect can cause the round trip, thus there will be a latency.

The target URL will be processed by the different domain/Web server, not from your application server.

So Server.Transfer would be the best option for this redirection operation.