ASP.Net MVC将部分视图从控制器重定向到不同控制器的完整视图

时间:2022-06-05 04:03:05

Ok. So I have an issue where I need to do some authorization checks inside the controller action.

好。所以我有一个问题,我需要在控制器操作中进行一些授权检查。

There are authorization roles, but it can exist that someone has TypeOnePayment, but not TypeTwo

有授权角色,但可能存在某人有TypeOnePayment,但没有TypeTwo

[Authorize(Roles = "TypeOnePayment;TypeTwoPayment")]
public ActionResult EnterRevenue(PaymentType payment)
{
    payment = "TypeOne"; // This exists for show only.
    var permission = string.Concat(payment,"Permission");
    if (!SecurityUtility.HasPermission(permission))
    {
        return View("Unauthorized", "Error");
    }
    return this.PartialView("_EnterRevenue");
}

But since this is returning the partial view, the "Error" screen only appears in the partial view portion of the page. Is there a way to redirect to an entirely new page?

但由于这将返回局部视图,因此“错误”屏幕仅出现在页面的局部视图部分中。有没有办法重定向到一个全新的页面?

EDIT: EnterRevenue is being retrieved through an ajax call. So just the html is being returned and it's being placed in the view it was called from.

编辑:通过ajax调用检索EnterRevenue。所以只返回html并将其放置在调用它的视图中。

3 个解决方案

#1


5  

You can redirect to some other action :

您可以重定向到其他一些操作:

public ActionResult EnterRevenue
{
    if (!SecurityUtility.HasPermission(permission))
    {
        return View("Unauthorized", "Error");
    }
    return RedirectToAction("NotAuthorized","Error");
}

Assume we have ErrorController with action NotAuthorized which returns normal View which displays you are not authorized to view this page.

假设我们有带动作NotAuthorized的ErrorController,它返回普通视图,显示您无权查看此页面。

If you need this check on every action, then you need to implement custom action filter attribute in which you will have to check if it is normal request redirect else return staus as json and redirect from client side. See asp.net mvc check if user is authorized before accessing page

如果您需要对每个操作进行此检查,那么您需要实现自定义操作过滤器属性,在该属性中您必须检查它是否是正常请求重定向,否则返回staus作为json并从客户端重定向。在访问页面之前,请参阅asp.net mvc检查用户是否获得授权

Here is a chunk of code:

这是一大堆代码:

public class AuthorizationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string actionName = filterContext.ActionDescriptor.ActionName;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;


            if (filterContext != null)
            {
                HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
                var userSession = objHttpSessionStateBase["userId"];
                if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession))
                {
                    objHttpSessionStateBase.RemoveAll();
                    objHttpSessionStateBase.Clear();
                    objHttpSessionStateBase.Abandon();
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.HttpContext.Response.StatusCode = 403;
                        filterContext.Result = new JsonResult { Data = "LogOut" };
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Home/Index");
                    }

                }


                else
                {

                    if (!CheckAccessRight(actionName, controllerName))
                    {
                        string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);

                        filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
                    }
                    else
                    {
                        base.OnActionExecuting(filterContext);
                    }
                }


            }

        }
 }

and use it on action like this:

并在这样的行动中使用它:

[Authorization]
public ActionResult EnterRevenue
{
    return this.PartialView("_EnterRevenue");
}

#2


0  

I think what you need can be boiled down to a way for the ajax call to behave differently based on what you are returning to it. The best I have found for doing this can be summarized as follows:

我认为你需要的东西可以简化为ajax调用的方式,根据你返回它的方式表现不同。我发现这样做的最好结论可归纳如下:

  • When you detect that you have no permission, add a model state error to your model.
  • 当您检测到您没有权限时,请向模型添加模型状态错误。

  • Override the OnActionExecuted (Hopefully all your controllers inherit from a base one so you can do it in one place, if not it might be a good idea to implement that now). In the override, check if the request is ajax and model state is not valid (if you want you can check for the specific error you added in the action method), change the request status to a 4xx status.
  • 覆盖OnActionExecuted(希望你的所有控制器都从一个基础继承,这样你就可以在一个地方进行,如果不是,那么现在实现它可能是个好主意)。在覆盖中,检查请求是否为ajax且模型状态无效(如果您希望可以检查在操作方法中添加的特定错误),请将请求状态更改为4xx状态。

  • In the OnFailure of your ajax call, you can redirect to the error page using javascript code.
  • 在ajax调用的OnFailure中,您可以使用javascript代码重定向到错误页面。

#3


0  

Or just use a standard redirect call. This should work everywhere (just don't do it inside of a using statement or it will throw an exception in the background):

或者只使用标准的重定向呼叫。这应该适用于任何地方(只是不要在using语句中执行它,否则它将在后台抛出异常):

Response.Redirect("/Account/Login?reason=NotAuthorised", true);                         

#1


5  

You can redirect to some other action :

您可以重定向到其他一些操作:

public ActionResult EnterRevenue
{
    if (!SecurityUtility.HasPermission(permission))
    {
        return View("Unauthorized", "Error");
    }
    return RedirectToAction("NotAuthorized","Error");
}

Assume we have ErrorController with action NotAuthorized which returns normal View which displays you are not authorized to view this page.

假设我们有带动作NotAuthorized的ErrorController,它返回普通视图,显示您无权查看此页面。

If you need this check on every action, then you need to implement custom action filter attribute in which you will have to check if it is normal request redirect else return staus as json and redirect from client side. See asp.net mvc check if user is authorized before accessing page

如果您需要对每个操作进行此检查,那么您需要实现自定义操作过滤器属性,在该属性中您必须检查它是否是正常请求重定向,否则返回staus作为json并从客户端重定向。在访问页面之前,请参阅asp.net mvc检查用户是否获得授权

Here is a chunk of code:

这是一大堆代码:

public class AuthorizationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string actionName = filterContext.ActionDescriptor.ActionName;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;


            if (filterContext != null)
            {
                HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
                var userSession = objHttpSessionStateBase["userId"];
                if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession))
                {
                    objHttpSessionStateBase.RemoveAll();
                    objHttpSessionStateBase.Clear();
                    objHttpSessionStateBase.Abandon();
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.HttpContext.Response.StatusCode = 403;
                        filterContext.Result = new JsonResult { Data = "LogOut" };
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Home/Index");
                    }

                }


                else
                {

                    if (!CheckAccessRight(actionName, controllerName))
                    {
                        string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);

                        filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
                    }
                    else
                    {
                        base.OnActionExecuting(filterContext);
                    }
                }


            }

        }
 }

and use it on action like this:

并在这样的行动中使用它:

[Authorization]
public ActionResult EnterRevenue
{
    return this.PartialView("_EnterRevenue");
}

#2


0  

I think what you need can be boiled down to a way for the ajax call to behave differently based on what you are returning to it. The best I have found for doing this can be summarized as follows:

我认为你需要的东西可以简化为ajax调用的方式,根据你返回它的方式表现不同。我发现这样做的最好结论可归纳如下:

  • When you detect that you have no permission, add a model state error to your model.
  • 当您检测到您没有权限时,请向模型添加模型状态错误。

  • Override the OnActionExecuted (Hopefully all your controllers inherit from a base one so you can do it in one place, if not it might be a good idea to implement that now). In the override, check if the request is ajax and model state is not valid (if you want you can check for the specific error you added in the action method), change the request status to a 4xx status.
  • 覆盖OnActionExecuted(希望你的所有控制器都从一个基础继承,这样你就可以在一个地方进行,如果不是,那么现在实现它可能是个好主意)。在覆盖中,检查请求是否为ajax且模型状态无效(如果您希望可以检查在操作方法中添加的特定错误),请将请求状态更改为4xx状态。

  • In the OnFailure of your ajax call, you can redirect to the error page using javascript code.
  • 在ajax调用的OnFailure中,您可以使用javascript代码重定向到错误页面。

#3


0  

Or just use a standard redirect call. This should work everywhere (just don't do it inside of a using statement or it will throw an exception in the background):

或者只使用标准的重定向呼叫。这应该适用于任何地方(只是不要在using语句中执行它,否则它将在后台抛出异常):

Response.Redirect("/Account/Login?reason=NotAuthorised", true);