为什么cookie请求在mvc控制器中为null返回?

时间:2016-01-04 13:44:08

标签: c# asp.net-mvc

我的登录methot, 输入cookie传入数据

public async Task<ActionResult> Login(string username, string password)
{
    try
    {
        RepairService.EmployeeServiceClient srv = new RepairService.EmployeeServiceClient();
        var CurrentEmployee = await Task.Run(() => srv.LoginEmployee(username, password));

        if (CurrentEmployee != null)
        {
            var model = new EmployeeDetail
            {
                EmloyeeId = CurrentEmployee.EmployeeId,
                //...//
            };

            HttpCookie cookie = new HttpCookie("userCookie");
            cookie.Value = JsonConvert.SerializeObject(model);
            cookie.Expires = DateTime.Now.AddDays(1);

            Response.Cookies.Add(cookie);

            return Json(model);
        }
    }
    catch (Exception)
    {
        return Json(null);
    }

    return Json(false);
}

因此,您可以控制用户何时登录cookie不为空。

public ActionResult IsLoggedIn()
{
    return Json(Request.Cookies["userCookie"] != null && Request.Cookies["userCookie"].Value != "");
}

当我调用获取此方法的值时,Request为null。我在哪里可以犯错误?

public ActionResult GetCurrentUser()
{
    if (Request.Cookies["userCookie"] != null && Request.Cookies["userCookie"].Value == "Test")
    {
        var employee = (EmployeeDetail)JsonConvert.DeserializeObject(Request.Cookies["userCookie"].Value);

        return Json(employee);
    }        

    return Json(false);       
}

1 个答案:

答案 0 :(得分:0)

在我看来,您正在以错误的方式进行身份验证。您不应该在Controller中为此负责创建一个Action。您必须创建一个ActionFilter,并装饰您的Actions或您的Controller,或者甚至全局注册此过滤器以验证每个请求。例如:

<强> ActionFilter

public class AuthorizedFilter : ActionFilterAttribute
{   
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Do your logic here
        var cookieValue = filterContext.HttpContext.Request.Cookies["userCookie"]).FirstOrDefault();

        if(cookieValue != null)
            return;

        filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary
                        {
                            {"controller", "Home"},
                            {"action", "Login"},
                        });
    }
}

<强>控制器

您可以在控制器级别使用,这意味着它将适用于所有操作

[AuthorizedFilter]
public class SomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

或者您可以在动作级别使用

public class SomeController : Controller
{
    [AuthorizedFilter]
    public ActionResult Index()
    {
        return View();
    }
}