7

I am building a fluent interface and would like to call the code below outside my controller...

return RedirectToAction("Activity");

How would I design this method? I have:

    public FluentCommand RedirectOnSuccess(string url)
    {
        if (IsSuccess)
            ;// make call here...

        return this;
    }

Note: IsSuccess is set here:

public FluentCommand Execute()
        {
            try
            {
                _command.Execute();
                IsSuccess = true;
            }
            catch (RulesException ex)
            {
                ex.CopyTo(_ms);
                IsSuccess = false;
            }
            return this;
        }

I call my fluent interface:

var fluent = new FluentCommand(new UpdateCommand(param,controller,modelstate)
.Execute()
.RedirectOnSucess("Actionname");
Haroon
  • 3,292
  • 6
  • 39
  • 73

1 Answers1

4

You could store an instance of the HttpContextBase as a field inside your fluent interface and when you need to redirect:

var rc = new RequestContext(context, new RouteData());
var urlHelper = new UrlHelper(rc);
context.Response.Redirect(urlHelper.Action(actionName), false);
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
  • Thanks, I allready pass in the controller and store it as a field and simply used _controller.HttpContext. – Haroon Aug 11 '11 at 09:59
  • Out of curiosity do I use the overload: var urlHelper = new UrlHelper(rc); to pass in route data? e.g. taskid = 34 – Haroon Aug 11 '11 at 10:01
  • @Haroon, you could use it like this: `urlHelper.Action(actionName, new { id = taskid })` – Darin Dimitrov Aug 11 '11 at 10:05
  • You can get the current HttpBaseContext using `var context = new HttpContextWrapper(HttpContext.Current)`. (http://stackoverflow.com/a/3472045/37147) – Jan Aagaard Oct 17 '13 at 08:38
  • The code sample from question expect to return value. But solution wont has return construction (Redirect is void). – Gilberto Alexandre Oct 11 '17 at 13:36