gpt4 book ai didi

c# - HTTP 错误 401.0 - 未经授权

转载 作者:行者123 更新时间:2023-11-30 22:20:25 25 4
gpt4 key购买 nike

我有这 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;
}
}

在我的 Controller 中我有这个:

 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 - 未经授权您无权查看此目录或页面。

我认为 session 未创建。我该怎么办?

最佳答案

这听起来像是您没有正确处理请求/路由的 IIS 配置,因此 IIS 没有使用 MVC 路由来选择正确的 Controller ,而是看到了目录的路径并抛出未经授权的消息,因为目录列表被禁用。

如何设置它在某种程度上取决于您运行的 IIS 版本。从技术角度来看,配置基本相同,但由于管理控制台经历了从 6 到 7 的巨大变化。如何在 IIS7(+) 中执行此操作已被优先询问,而不是重写答案,我认为它符合精神这个社区最好转发到answer

关于c# - HTTP 错误 401.0 - 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15010526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com