我如何从void方法重定向到视图? [英] how can i redirect from void method to a view?

查看:192
本文介绍了我如何从void方法重定向到视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


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

        }
        else
        {
            //redirect to error view
        }

    }

我尝试使用Redirect("Index");但它不起作用,是否可以从void方法重定向到视图

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

推荐答案

您不能从返回void的方法进行重定向.为了重定向,必须返回ActionResult,并且由于此方法未返回 ,因此您显然无法实现该目标.

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.

将动作的返回类型设置为void只是一种简单的说法,即它返回状态码为200且没有响应主体的响应.如果实际上不是这种情况(因为这里不是),则您不应具有void的返回类型.在这里,唯一可能的响应是重定向,因此您的操作的返回类型应为ActionResultRedirectResult.不过,最好对所有内容都使用ActionResult,因为它是所有其他类型的结果的基类.您甚至可以通过执行return new EmptyResult();或仅执行return null;来实现与使用void相同的功能.

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;.

这篇关于我如何从void方法重定向到视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆