asp.net mvc - .NET MVC: How to redirect response within a helper method -


i have code common number of controller actions pulled out private "helper" method consolidation. method expected "get" object me, though performs sanity/security checks , potentially redirect user other actions.

private thingy getthingy(int id) {     var thingy = some_call_to_service_layer(id);      if( null == thingy )         response.redirect( anotheractionurl );      // ... many more checks, more complex null check      return thingy; }  public actionresult actionone(int id) {     var thingy = getthingy(id);     // more stuff     return view(); }  // ... n more actions  public actionresult actionm(int id) {     var thingy = getthingy(id);     // more stuff     return view(); } 

this functions exception elmah notifies me of exception:

system.web.httpexception: cannot redirect after http headers have been sent. 

so, question is: there more correct way trying do? essentially, want cause current action stop processing , instead return redirecttorouteresult.

you cannot call response.redirect() in action without breaking flow of execution causing error. instead can return redirecttorouteresult object or redirectresult object. in action

return redirect("/path"); //or return redirecttoaction("actionname"); 

as in case want return thingy object need seperate out logic. following (i'm assuming want redirect different actions otherwise oenning's code work)

public actionresult get(int id) {    var thingy = getthingy(id);    var result = checkthingy(thingy);   if (result != null) {     return result;   }    //continue... }  [nonaction] private actionresult checkthingy(thingy thingy) {    //run check on thingy   //return new redirectresult("path");    //run check   //new redirectresult("different/path");    return null; } 

update put code in extension method or base controller class

public static class thingyextensions {    public static actionresult check(this thingy thingy) {     //run checks here   }  } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -