2016-05-23 46 views
1

我有一個Identity 3.0項目。我已經設置了一個動態菜單,它也能正常工作,並根據您所處的角色顯示不同的菜單列表。asp.net核心MVC 6授權用戶的不同主頁

我想授權用戶擁有不同的主頁。如果您未經授權,您應該按照正常方式看到「/ Home/Index」。

如果您已獲得授權(以用戶身份登錄並記住您..),您應該始終將其定向到授權用戶的其他主頁...「/ Scheduling/Index」。

我樹立了一個AuthorizeFilter

  services.AddMvc(setup => 
     { 
      setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); 
     }); 

所以,除非你是授權,如果你嘗試訪問任何控制器沒有你得到一個登錄頁面:

[AllowAnonymous] 

在開始。 ..例如HomeController有這個在開始...

我發現this在Stackoverflow和嘗試它在啓動類,但它不工作。

  services.Configure<CookieAuthenticationOptions>(options => 
     { 
      options.LoginPath = new PathString("/Scheduler/Index"); 
     }); 

根據用戶是否登錄或未登錄,我如何擁有兩個不同的主頁?

回答

3

你(至少)兩種方式:

1)返回不同的視圖名稱從 '索引' 行動(取決於用戶狀態):

[AllowAnonymous] 
public IActionResult Index() 
{ 
    // code for both (anonymous and authorized) users 
    ... 

    var shouldShowOtherHomePage = ... // check anything you want, even specific roles 
    return View(shouldShowOtherHomePage ? "AuthorizedIndex" ? "Index", myModel); 
} 

這個人是好當您的Index方法沒有「重」邏輯,對於匿名/授權用戶不同,並且在一種方法中不會有兩個「分支」代碼。

2)重定向授權用戶其他行動Index

[AllowAnonymous] 
public IActionResult Index() 
{ 
    var shouldShowOtherHomePage = ... 
    if (shouldShowOtherHomePage) 
    { 
     return RedirectToAction("AuthorizedIndex", "OtherController"); 
    } 

    // code for anonymous users 
    .... 
} 

使用此選項,當你不希望混合兩種邏輯的一種方法內流動,或者你的行爲是在不同的控制器。

+0

嗨@Dimitry和其他..有沒有一種方法可以做到這一點,只是從StartUp.cs類使用過濾器等我寧願它在啓動如果可能 – si2030

+0

您可以使用[動作過濾器](https:/ /docs.asp.net/en/latest/mvc/controllers/filters.html#action-filters)與特定於操作/控制器的邏輯或[創建自己的中間件](https://docs.asp.net/en/latest /fundamentals/middleware.html#writing-middleware),如果您有特定於網址的邏輯(例如,將用戶重定向到基於當前URL和其他一些條件的其他網址)並放置在Mvc中間件之前。兩者都在'Startup.cs'中配置 – Dmitry