当从jQuery发送ajax请求时,我在知道用户是否经过身份验证时遇到了问题。
当用户从其浏览器执行常规请求并且设置了aspxauth cookie时,HttpContext.User.Identity不为空。当用户尝试从jQuery执行ajax请求时,根本不会设置aspxauth。
我的Web.Config
<authentication mode="Forms">
<forms loginUrl="~/" />
</authentication>设置FormsAuthentication Cookie
var cookie = new AuthCookie
{
UserId = user.UserId,
Email = user.Email,
Name = user.Name,
RememberMe = createPersistentCookie,
TimeZone = user.TimeZone,
CompanyId = user.CompanyId,
Roles = new List<string> { user.Role ?? "user" }
};
string userData = JsonConvert.SerializeObject(cookie);
var ticket = new FormsAuthenticationTicket(1, cookie.Email, DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
createPersistentCookie, userData);
string encTicket = FormsAuthentication.Encrypt(ticket);
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.Add(FormsAuthentication.Timeout) };
_httpContext.Response.Cookies.Add(httpCookie);当我通过我的broser发出请求时,会出现身份验证cookie:

每当我使用$.get()通过javascript发出请求,或者通过javascript加载javascript脚本/任何其他请求时,我得到:

奇怪的是,在另一个ASP应用程序上,我使用的是WebSecurity,它工作得很好。身份验证cookie总是从客户端发送回服务器。对于这个ASP MVC 5应用程序,当我尝试使用FormAuthentication时,我无法让AuthCookie处理所有请求。
发布于 2015-02-24 04:12:13
您仍然可以使用Authorize等来修饰您的类/方法。如果您希望检查控制器方法内部,则可以访问从System.Web.Mvc.Controller或System.Web.Http.ApiController继承的User属性,这取决于您的控制器风格:
//
// Summary:
// Returns the current principal associated with this request.
//
// Returns:
// The current principal associated with this request.
public IPrincipal User { get; set; }它的使用方法如下:
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
// user has access - process request
}编辑:
下面是一个具有ajaxable方法的ApiController示例,该方法使用控制器的User属性而不是HttpContext的属性:
public class HelloController : ApiController
{
[HttpGet]
public IHttpActionResult HelloWorld()
{
try
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
return Ok("Hello There " + User.Identity.Name + "!");
}
else
{
return Ok("Hello There Anonymous!");
}
}
catch { throw; }
}
}https://stackoverflow.com/questions/28680571
复制相似问题