asp.net mvc validate [HttpPost] ActionResult()

时间:2014-10-28 19:15:02

标签: c# asp.net-mvc

我需要在控制器中实现ActionFilterAttribute [POST] ActionResult()。问题是,如果验证失败,我会尝试“重定向”到页面......但它不起作用。验证运行,但随后返回ActionResult()下一行,最后返回视图时,才“重定向”到验证中列出的页面。最终我需要的是停止ActionResult()语句并“重定向”到验证中列出的页面。我尝试了OnActionExecuting()OnActionExecuted(),但没有使用任何

我需要......

filterContext.HttpContext.Response.Redirect (loginUrl, true);

逃跑,“重定向”指示的页面

我的代码:

[HelperSomeValidations("")]
[HttpPost]
public ActionResult Create(Pais pais)
{
  try
  {
    PaisBLL.saveNew(pais);
  }
  catch (Exception ex) 
  {
    ViewBag.error = ex;
    return View(“Error”);
  }
  return RedirectToAction(“Index”);
}

public class HelperSomeValidations : ActionFilterAttribute
{

  public HelperSomeValidations(String permiso)
  {
    this.permiso = permiso;
  }

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    var user = filterContext.HttpContext.Session["coco"];
    if (user == null) //validates if the user just login
    {
      //send them off to the login page
      var url = new UrlHelper(filterContext.RequestContext);
      var loginUrl = url.Content(“~/Usuario/Login”);
      filterContext.HttpContext.Response.Redirect(loginUrl, true);
    }
    else
    {
      if (permission != “”)
      {
        //does some validations with “permission”
      }
    }
 }

}

THKS!

2 个答案:

答案 0 :(得分:1)

我知道这并没有解决你发布的问题,但我觉得这是一个更好的解决方案。我个人会在这里使用AuthoriseAttribute,因为这是它设计的内容。

public class Authorise : AuthorizeAttribute
{
    private readonly string _permissionSystemName;

    public Authorise()
    {
    }

    public Authorise(string permissionSystemName)
    {
        _permissionSystemName = permissionSystemName;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //DO some logic and return True or False based on whether they are allowed or not.

        return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary(
                new
                {
                    area = filterContext.HttpContext.Request.RequestContext.RouteData.Values["area"],
                    controller = "Generic",
                    action = "PermissionDenied"
                })
            );
    }
}

用法如下:

[Authorise("SomePermissionName")]
public class MyController : Controller
{

}

答案 1 :(得分:0)

您需要将filterContext.Result设置为filterContext.HttpContext.Response.Redirect(loginUrl, true),而不是调用RedirectResult