使用自定义操作筛选器属性时出现意外行为

时间:2015-04-28 16:06:24

标签: asp.net-mvc asp.net-mvc-4

我正在尝试重现与锅炉板帐户操作过滤器相同的功能,但具有执行操作所需的不同值。我遇到了一个奇怪的事件。这是我的ActionFilterAttribute定义:

public class RequireMemberSelectionAttribute : ActionFilterAttribute
{
    /// <summary>
    /// When the decorated action is executing, redirect to the member selection view if a member is not selected.
    /// </summary>
    /// <param name="a_filterContext">Filter context.</param>
    public override void OnActionExecuting(ActionExecutingContext a_filterContext)
    {
        if ((Session.Current.Preferences.MemberID ?? 0) > 0)
            return;

        String returnUrl = null;
        if (a_filterContext.HttpContext.Request.Url != null)
            returnUrl = a_filterContext.HttpContext.Request.Url.PathAndQuery;

        a_filterContext.Redirect("Builder", "ListMembers", new { ReturnUrl=returnUrl });
    }
}

这就是我在代码中使用它的方式。我想在进入SelectArea操作之前确保会话具有成员ID:

    // GET: Builder/SelectArea
    [RequireMemberSelection]
    public async Task<ActionResult> SelectArea()
    {
        var memberId = _session.Preferences.MemberID ?? 0;

        return View();
    }

    // GET: Builder/ListMembers/{returnUrl}
    [Route("Builder/ListMembers")]
    public async Task<ActionResult> ListMembers(String returnUrl = "")
    {
        var members = await _repository.GetMembers();

        ViewBag.ReturnUrl = returnUrl;

        return View(members);
    }

    // GET: Builder/SelectMember/{id}
    [Route("Builder/SelectMember/{id}")]
    public ActionResult SelectMember(int id, String returnUrl = "")
    {
        _session.Preferences.MemberID = id;

        if (!String.IsNullOrEmpty(returnUrl))
            return RedirectPermanent(returnUrl);

        return RedirectToAction("Index");
    }

意外行为是,当ListMembers.cshtml视图上的链接被点击时,它不会转到SelectMember操作,而是尝试转到SelectArea,然后重新开始。

以下是ListMembers.cshtml的确切链接。我从浏览器中呈现的页面直接复制了它:

  

http://localhost:61286/Builder/SelectMember/1?returnUrl=%2FBuilder%2FSelectArea

我觉得我不理解动作过滤器的某些内容。

以下是我在剃刀视图中生成链接的方法:

@Html.ActionLink("Test Link", "SelectMember", new { id = 1, returnUrl = ViewBag.ReturnUrl })

0 个答案:

没有答案