在PartialViewResult()方法中重定向页面

Dew*_*uka 2 .net c# asp.net-mvc-2

嗨我正在尝试使用PartialViewResult方法在某些条件不是页面时重定向页面.但我无法做到.我的代码如下:

public PartialViewResult Visit()
{    
    int visit = 0;
    if (base.IsLoggedIn() == true)
    {
        visit++;
    }
    else
    {
        // toDO redirect to home/index page
    }
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*ein 5

您提供的代码段将无法编译.您必须从所有代码路径返回结果.尝试这样的事情:

public ActionResult Visit()
{
    int visit = 0;

    if (base.IsLoggedIn() == true)
    {
        visit++;
        return PartialView();
    }
    else
    {
        return RedirectToAction("ACTION_NAME_GOES_HERE");
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

我相信我现在明白你想要完成的事情.如果未登录的用户发出ajax请求,您希望浏览器重定向用户.我建议修改你的动作方法如下:

public ActionResult Visit()
{
    int visit = 0;

    if (base.IsLoggedIn())
    {
        visit++;
        // whatever else needs to be done
        return PartialView();
    }
    else
    {
        // Note that this could be done using the Authorize ActionFilter, using
        // an overriden Authorize ActionFilter, or by overriding OnAuthorize().
        if (!base.IsLoggedIn())
            return new HttpUnauthorizedResult();
    }
}
Run Code Online (Sandbox Code Playgroud)

假设您已在web.config中配置,响应将是302重定向,这不是您在此方案中所需的.请参阅Phil Haack的博客文章,其中解释了如何防止此ASP.NET行为并返回401 Unauthorized响应:

http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx

然后,假设您使用jQuery发出AJAX请求,您可以处理401响应:

$.ajax({
    url: '/your_controller/visit',
    type: 'GET',
    statusCode: {
        200: function (data) {
            // data = your partialview
        },
        401: function (data) {
            location.href = '/the_path/to_redirect/to';
        }
    }
});
Run Code Online (Sandbox Code Playgroud)