2013-02-21 153 views
2

我有這4類:HTTP錯誤401.0 - 未經授權

public class Personal 
     { 
      public int Id { get; set; } 
      public string Name { get; set; } 
     } 

public class LoginRepository 
    { 
     Context context = new Context(); 
     public Personal GetByUsernameAndPassword(Personal user) 
     { 
      return context.Personals.Where(u => u.Name==user.Name).FirstOrDefault(); 
     } 
    } 

public class LoginApplication 
    { 
     LoginRepository userRepo = new LoginRepository(); 
     public Personal GetByUsernameAndPassword(Personal user) 
     { 
      return userRepo.GetByUsernameAndPassword(user); 
     } 
    } 

public class SessionContext 
    { 
     public void SetAuthenticationToken(string name, bool isPersistant, Personal userData) 
     { 
      string data = null; 
      if (userData != null) 
       data = new JavaScriptSerializer().Serialize(userData); 

      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddYears(1), isPersistant, data); 

      string cookieData = FormsAuthentication.Encrypt(ticket); 
      HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieData) 
      { 
       HttpOnly = true, 
       Expires = ticket.Expiration 
      }; 

      HttpContext.Current.Response.Cookies.Add(cookie); 
     } 

     public Personal GetUserData() 
     { 
      Personal userData = null; 

      try 
      { 
       HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; 
       if (cookie != null) 
       { 
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 

        userData = new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(Personal)) as Personal; 
       } 
      } 
      catch (Exception ex) 
      { 
      } 

      return userData; 
     } 
    } 

而且在我的控制器我有這樣的:

public class HomeController : Controller 
    { 
     LoginApplication userApp = new LoginApplication(); 
     SessionContext context = new SessionContext(); 
     public ActionResult Index() 
     { 
      return View(); 
     } 
     [HttpPost] 
     public ActionResult Index(Personal user) 
     { 
      var authenticatedUser = userApp.GetByUsernameAndPassword(user); 
      if (authenticatedUser != null) 
      { 
       context.SetAuthenticationToken(authenticatedUser.Name, false, authenticatedUser); 
       return RedirectToAction("Index", "Asp"); 
      } 
      return View(); 
     } 
    } 

但問題是這樣的,即使我用正確的名稱登錄我看到此錯誤:

HTTP錯誤401.0 - 未授權 您沒有權限查看此目錄或頁面。

我認爲會議沒有創建。 我該怎麼辦?

回答

3

它聽起來像IIS配置,你不正確地處理請求/路由,所以而不是使用MVC路由來選擇正確的控制器IIS會看到目錄的路徑並導致未經授權,因爲目錄列表被禁用。

如何設置它取決於您運行的IIS版本。從技術角度來看,配置基本上是相同的,但是自從管理控制檯經歷了從6到7的劇烈變化之後。如何在IIS7(+)中做到這一點已被非常不情願地提出,而不是重寫答案,我認爲它服務於精神這個社區更好轉發到answer

+0

那麼,我該如何解決呢? – 2013-02-21 19:55:30

+0

@HamidReza看到我連接到的答案 – 2013-02-22 08:04:47

+0

非常感謝。收聽它。) – 2013-02-22 11:29:47