2014-01-10 104 views
1

我在web配置中使用以下設置來防止匿名訪問我的網站。如何只允許匿名訪問網站的首頁?

<authorization> 
    <deny users="?"/> 
</authorization> 

我想只允許匿名訪問我的網站的首頁。我如何實現這一目標?我正在使用ASP .NET MVC 3.5。

回答

1
,如果你希望實現對控制器/動作匿名訪問您必須啓用它在

你Web.Config中:

<location path="Home/Index"> 
    <system.web> 
    <authorization> 
     <allow users="?" /> 
    </authorization> 
    </system.web> 
</location> 

一個純粹的MVC應用程序更好的方法是使用授權屬性,並能夠訪問所有用戶在web.config。

public void Application_BeginRequest() 
{ 
    if (Request.AppRelativeCurrentExecutionFilePath == "~/") 
     HttpContext.Current.RewritePath("/Home/Index"); 
} 

它正在工作,我檢查了。

+0

這將無法正常工作。如果我把路徑設置爲「Home/Index」,它將允許www.foo.com/home/index,而不是www.foo.com。 – RWendi

+0

只是嘗試使用此自定義屬性..http://blog.tomasjansson.com/securing-your-asp-net-mvc-3-application – Nilesh

+0

@RWendi檢查編輯答案 – Nilesh

0

設置你的登錄URL到您的主頁,就像這樣:

<authentication mode="Forms"> 
    <forms loginUrl="/Home/Index" /> 
</authentication> 

將匿名用戶重定向到登錄頁面。

或者你可以在你的行動使用AllowAnonymous屬性(在家庭控制器Index操作或無論它是)

[AllowAnonymous] 
public ActionResult Index() 
{ 
    ... 
} 
+0

這是如何解決我的問題?我想讓匿名用戶訪問我的首頁。不會將它們重定向到登錄頁面。 – RWendi

+0

您正在用您的主頁網址替換登錄頁面的網址,以便您的主頁成爲您的登錄頁面。 –

+0

但我不希望我的主頁成爲我的登錄頁面。 :) – RWendi