views:

200

answers:

1

I am calling a static method within my business logic layer that, for purposes I won't mention here, needs to do the redirecting itself rather returning information back to the controller to do the redirect.

I figure I need to use the HttpContext object but am struggling with creating the route. I can't simply do context.Response.Redirect("someController/someMethod) because I need to include parameters for the action controller that I"m sending the user to.

Assuming this is correct:

HttpContext context = HttpContext.Current;

Can anyone please provide some syntax help with how to create a route using an object like:

new { Controller = "MyController", action = "Index", OtherParm="other value" }

TIA

+2  A: 

Very ugly, anti-MVC, don't do in business layer, etc... but since you are asking:

var context = new RequestContext(
    new HttpContextWrapper(System.Web.HttpContext.Current), 
    new RouteData());
var urlHelper = new UrlHelper(context);
var url = urlHelper.Action("Index", new { OtherParm = "other value" });
System.Web.HttpContext.Current.Response.Redirect(url);
Darin Dimitrov
I initially answered but deleted when I saw yours, agreed very anti MVC but better than my response
Pharabus
great thanks much. I got it working using your sample as a guide...did it a bit differently, but couldn't have done it w/o your assistance. Basically I'm doing a security check against the database and throwing an exception on the BLL if it doesn't pass which is why I need to redirect from there. YOu say very anti-MVC....where would you suggest I put this check to have it throw a custom exception? On the controller?
Kyle
I suggest you throwing the exception in the BL, catching it in the controller and perform the redirect **in** the controller.
Darin Dimitrov
ok thanks again.
Kyle
sorry to beat a dead horse here. But can you provide me with an argument as to why this logic should be put in the controller? I'm just trying to wrap my head around the MVC stuff and don't fully understand why it's a bad idea to put this in the BLL....
Kyle
Because the BLL is destined to be used in different kind of applications. Imagine for example that you need to develop a WinForms application that needs functionality in your BLL, or expose this functionality to partners as a SOAP web service (because your partners use Java). It makes absolutely no sense to talk about HttpContext, redirect and web stuff in a windows application. Every time you reference System.Web.dll and use HttpContext.Current in the business layer you narrow its usage to only web applications and in your case even narrower: ASP.NET MVC web applications.
Darin Dimitrov