Only allow access to action if redirected from specific action

感情迁移 提交于 2019-12-04 03:15:41

问题


Is there a good way to restrict the access to an action, so you can only access it, if you were redirected from another action. For example:

    [HttpPost]
    public virtual ActionResult Create(MyViewModel vm)
    {            
        if (ModelState.IsValid)
        {
            // do some work

            return RedirectToAction("CreateSuccess");
        }
        else
        {
            return View(vm);
        }
    }


    public virtual ActionResult CreateSuccess()
    {
        // only allow execution if you were redirected from Action "Create" 
    }

回答1:


An easy way would be to store a flag in TempData in the first method and check that the flag exists in the method that is redirected to.
TempData is there to pass state information between action requests and will only last the duration of the request so you will not need to worry about clearing it down.




回答2:


There is no way to know the "from" action unless you include parameters indicating such. The easiest way is to append a "SourceAction" or "FromAction" parameter and check it in the "destination" action.




回答3:


The question is, why do you want to do that? Maybe there is a better solution for your primary problem.

Anyway, you can use the HttpContext.Current.Request.UrlReferrer Property to check the previous page Url.




回答4:


First solution

You could just do this:

[HttpPost]
public virtual ActionResult Create(MyViewModel vm)
{            
    if (ModelState.IsValid)
    {
        // do some work
        return this.CreateSuccess();
    }
    else
    {
        return View(vm);
    }
}

[NonAction]
public virtual ActionResult CreateSuccess()
{
    // do what's needed 
}

This last method will only be executed from other action methods. But it can't be executed per se.

Second solution

You could solve this by creating a custom action method selector attribute as well if you know you can reuse this. You could write a custom action method selector attribute that checks request referrer and uses appropriate method.

Read about custom action selector attributes.



来源:https://stackoverflow.com/questions/3864366/only-allow-access-to-action-if-redirected-from-specific-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!