在MVC中一起使用Ajax.ActionLink和ChildActionOnly失败

Ben*_*enk 2 asp.net-mvc razor asp.net-mvc-5

在我看来,我有 Ajax.ActionLink

@Ajax.ActionLink("Display Information", "Information"}, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "divCurrentView", InsertionMode = InsertionMode.Replace })

它调用替换div的局部视图.一切正常,但当我添加 [ChildActionOnly]到局部视图时,它永远不会被执行

[ChildActionOnly]
public PartialViewResult Information()
Run Code Online (Sandbox Code Playgroud)

有没有不同的使用方法Ajax.ActionLink[ChildActionOnly]一起使用?

我想阻止任何人使用URL导航到该操作

Kar*_*sla 7

ChildActionOnlyAttribute 只能与HTML扩展方法一起使用.

ChildActionOnly属性确保只能从视图中调用操作方法作为子方法.我们倾向于使用此属性来防止因用户请求而调用操作方法.

在您的情况下,而不是[ChildActionOnly]使用AjaxOnly如下所示的属性:

[AjaxOnly]
public PartialViewResult Information()
Run Code Online (Sandbox Code Playgroud)

这是你如何制作一个

public class AjaxOnlyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(!filterContext.HttpContext.Request.IsAjaxRequest())
            filterContext.HttpContext.Response.Redirect("/error/404");
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它

[AjaxOnly]
public PartialViewResult Information()
Run Code Online (Sandbox Code Playgroud)