how can i redirect from void method to a view?

…衆ロ難τιáo~ 提交于 2020-06-18 10:55:33

问题


    [HttpGet]
    public void verifyAccount(string id)
    {
        if (clientDB.verifyAccount(id)!="")
        {


           // Redirect("index");//redirect to index view

        }
        else
        {
            //redirect to error view
        }

    }

i try to use Redirect("Index"); but it does not work, Is it impossible to redirect to view from a void method


回答1:


You cannot redirect from a method that returns void. In order to redirect, you must return an ActionResult, and since this method returns nothing, you obviously cannot achieve that.

Setting the return type of an action to void is just a simplistic way of saying it returns a response with a 200 status code and no response body. If that's not actually the case, as it isn't here, then you should not have a return type of void. Here, the only response possible is a redirect, so your action should have a return type of either ActionResult or RedirectResult. It's generally better to just use ActionResult for everything though, as it's the base class for all other types of results. You can even achieve the same thing as if you used void by doing return new EmptyResult(); or simply return null;.




回答2:


Yes you can with HandleUnknownAction

RedirectToAction("Index").ExecuteResult(this.ControllerContext);



回答3:


Is it impossible to redirect to view from a void method?

Yes. Your action should return an ActionResult type and return the redirect (or view).




回答4:


its not right but you can use Response.Redirect("~/Home/Login");

but in some case it can happedn that antiforgerytokenm will throw exception...



来源:https://stackoverflow.com/questions/43739282/how-can-i-redirect-from-void-method-to-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!