繁体   English   中英

Asp.Net Core重定向到操作但不允许直接调用操作?

[英]Asp.Net Core redirect to action but not allow action to be called directly?

我有一种情况,我希望在结果成功时重定向/显示某个url / action但是如果有错误则返回查看。

例如,当someWork返回true时,我想用一些数据显示“成功页面”,但是当它为false时,我将返回页面并显示错误。

通常ChildAction可以做到,但在.Net Core中,它们似乎缺失了。

实现这一目标的最佳方法是什么? 我主要担心的是,如果有人在浏览器栏中将其写入,则不应直接访问“成功”路线/操作。

public IActionResult DoSomething()
{
    bool success = someWork();
    if (success)
    {
       // goto some action but not allow that action to be called directly
    }
    else
    {
       return View();
    }
}

一种解决方案(或更确切地说是一种解决方法)是使用临时数据来存储bool并在其他操作中进行检查。 像这样:

public IActionResult DoSomething()
{
    bool success=someWork();
    if(success)
    {
        TempData["IsLegit"] = true;
        return RedirectToAction("Success");
    }
    else
    {
        return View();
    }
}

public IActionResult Success
{
    if((TempData["IsLegit"]??false)!=true)
        return RedirectToAction("Error");
    //Do your stuff
}

ASP.NET Core有一个新功能View Components 视图组件由两部分组成,一个类和一个结果(通常是剃刀视图)。 视图组件无法直接作为HTTP端点访问,它们是从您的代码中调用的(通常在视图中)。 它们也可以从最适合您需要的控制器调用。 为成功消息创建剃刀视图

<h3> Success Message <h3>
Your Success Message...

创建相应的视图组件

public class SuccessViewComponent : ViewComponent
{
   public async Task<IViewComponentResult> InvokeAsync()
   {
       return View();
   }
}

请注意,视图名称和视图组件名称以及这些文件的路径遵循与控制器和视图非常相似的约定。 请参阅ASP.NET核心文档。

从操作方法调用视图组件

public IActionResult DoSomething()
{
    bool success=someWork();
    if(success)
    {
        return ViewComponent("Success");
    }
    else
    {
        return View();
    }
}

您可以将操作设为私有。

public IActionResult DoSomething()
{
    bool success = someWork();
    if (success)
    {
       // goto some action but not allow that action to be called directly
       return MyCrazySecretAction();
    }
    else
    {
       return View();
    }
}

private IActionResult MyCrazySecretAction()
{
    return View();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM