0

我有 AccountController 作为

[HttpPost]
public ActionResult Login(string user_name,string password)
{
    if (ModelState.IsValid)
    {
        var x = (from n in db.Customers
                 where n.User_Name==user_name && n.Password==password                         
                 select n).FirstOrDefault();
        if (x != null)
        {
            Session["UserName"] = x.First_Name;                                        
            return RedirectToAction("Products","Home");
        }
        else
        {
            @ViewBag.ErrorValidationFailed = "Invalid username or password";                    
            return View();
        }
    }
    return View();
}

和 HomeController

[Authorize]
public class HomeController : Controller
{ 
    //Some code here
}

现在,一旦验证凭据,我该怎么办?我希望用户能够访问 HomeController 中的操作方法。但是在验证凭据而不是重定向到 Products 操作方法之后,它会显示 401 错误。如果我在任何地方错了,请纠正我

4

3 回答 3

2

有两种方法可以做到这一点。

第一种方法:

一种方法是制作一个基本控制器并从需要经过身份验证的用户的基本控制器继承您的控制器:

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["UserName"] == null)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new JsonResult { Data = "LogOut", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            else
                filterContext.Result =  new RedirectResult("~/Account/Login");
        }

    }
}

然后从 BaseController 继承 HomeController:

public class HomeController : BaseController
{ 

}

第二种方法:

第二种方法是创建一个自定义操作过滤器属性并用它装饰您需要身份验证的操作:

public class AuthenticateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["UserName"] == null)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new JsonResult { Data = "LogOut", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            else
                filterContext.Result = RedirectToAction("Login", "Account");
        }
    }
}

并使用经过身份验证的用户应该访问哪些操作的属性来装饰您的操作:

public class HomeController : Controller
{
   [AllowAnonymous]
   public ActionResult AllowAllUserAction()
   {

   } 
   [Authenticate]
   public ActionResult SomeAction()
   {

   }
}
于 2014-12-30T07:33:42.753 回答
0

使用此代码,它应该可以工作

[HttpPost]
public ActionResult Login(string user_name,string password)
{
    if (ModelState.IsValid)
    {
        var x = (from n in db.Customers
                 where n.User_Name==user_name && n.Password==password                         
                 select n).FirstOrDefault();
        if (x != null)
        {
            Session["UserName"] = x.First_Name;    

            //Authenticating the user  
            FormsAuthentication.SetAuthCookie(x.First_Name, false);

            return RedirectToAction("Products","Home");
        }
        else
        {
            @ViewBag.ErrorValidationFailed = "Invalid username or password";                    
            return View();
        }
    }
    return View();
}
于 2014-12-30T08:23:15.430 回答
0
    [HttpPost]
    public ActionResult Login(FormCollection formCollection)
    {
        Credentials credentials = new Credentials();


        credentials.Username = formCollection["username"].ToString();
        credentials.Password = formCollection["password"].ToString();
        var result = ApiHelper.PostLogin<FRP.WebApp.Models.Credentials>(MicroService.Login, "/api/Authenticate/Login", credentials, credentials.Username, credentials.Password);
        ViewData["username"] = formCollection["username"];
        ViewData["password"] = formCollection["password"];

        if (result.Status == Sonata.Framework.Models.BusinessStatus.Ok)
        {
            ViewData["error"] = "";
            return View("About", result);
        }
        else
        {
            RegistrationViewModel model = new RegistrationViewModel();
            model.Years = ViewHelper.GetYears();
            ViewData["error"] = "InValid";
            return View("Index",model);
        }
    }
于 2017-09-25T10:07:52.137 回答