Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a Response.Redirect from a non-Web based project

Tags:

c#

asp.net

I have created a utility method that contains some try/catches in it. In those try/catches I need to redirect the customer using an HttpResponse redirect. I can't seem to figure out how to do this outside a web project. This utility class is referenced from my ASP.NET web project and so I'm just abstracting out some of the code into this utility class so I no longer have the request object.

I know I can use HttpWebRequest object for a lot of web related request tasks outside a web project, but could not seem to get any redirect method there to use after putting in a using System.Net; in my utility class.

like image 700
PositiveGuy Avatar asked Jan 24 '26 21:01

PositiveGuy


1 Answers

Top of your file:

using System.Web;

In your function:

HttpContext.Current.Response.Redirect("http://www.mysite.com/redirect");

This way does make your library dependant on the System.Web library, but your code isn't in a web project. It will grab the current HttpContext for the request it's called from. You'll probably want to do some null checking though, if this code is called from outside of a web-context you're going to get a NullReferenceException.

If you're using WCF there's a different context-object you want to use, I just can't remember what it is. OperationContext maybe?

like image 147
Aren Avatar answered Jan 27 '26 09:01

Aren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!