2017-02-07 51 views
5

我有一種情況,當結果成功時,我想重定向/顯示某個url/action,但如果出現錯誤,則返回到視圖。Asp.Net核心重定向到操作但不允許直接調用操作?

例如,當someWork返回true我想用一些數據顯示「成功的頁面」,但當它是假的時候,我會返回頁面並顯示錯誤。

通常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(); 
    } 
} 
+0

儘管您可能會這麼想,但您在以前的版本中無法使用'[ChildActionOnly]'方法 –

回答

3

一個解決方案(或者更確切地說,一個解決方法)是使用臨時數據存儲一個布爾值,並檢查它在你的其他行動。像這樣:

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 
} 
0

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(); 
    } 
} 
0

調用視圖組件您可以只作私人行動。

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(); 
}