HTTP错误401.0-未经授权
本文关键字:授权 错误 HTTP | 更新日期: 2023-09-27 18:00:23
我有这4个类:
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-未经授权您没有查看此目录或页面的权限。
我认为会议没有创建。我该怎么办?
在IIS配置中,您似乎没有正确处理请求/路由,因此IIS没有使用MVC路由来选择正确的控制器,而是看到了一个目录的路径,并抛出了一个未经授权的,因为目录列表被禁用。
如何设置取决于您正在运行的IIS版本。从技术角度来看,配置基本相同,但由于管理控制台经历了从6到7的剧烈变化。如何在IIS7(+)中做到这一点已被私下询问,我认为与其重写答案,不如转发答案