コード例 #1
0
        public ActionResult Login2(LoginViewModel2 model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var validateCode = Session["ValidateCode"] as string;

            if (string.IsNullOrWhiteSpace(validateCode) || validateCode != model.ValidateCode)
            {
                ModelState.AddModelError("", "Validate Code is incorrect.");
                return(View(model));
            }

            var result = SignInManager.PasswordSignIn(model.UserName, model.Password, false, false);

            if (result != SignInStatus.Success)
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return(View(model));
            }

            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult Login(LoginViewModel2 model, string returnUrl)
        {
            // JSON object to be sent to API for authentication
            var obj = new
            {
                grant_type = "password",
                username   = model.Email,
                password   = model.Password
            };
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(BASE_ADDRESS);
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "token");
                request.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");

                var responseTask = client.SendAsync(request);

                // HTTP POST
                //var responseTask = client.PostAsJsonAsync("token", json);
                responseTask.Wait();

                var response = responseTask.Result;
                if (response.IsSuccessStatusCode)
                {
                    var readTask = response.Content.ReadAsAsync <TokenViewModel>();
                    readTask.Wait();

                    token = readTask.Result;
                }
                else // Web api sent error response
                {
                    /* TODO: Logging */

                    ModelState.AddModelError(string.Empty, "Server error.");
                }
            }

            if (Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));
            }
            return(RedirectToAction("Index", "Home"));
        }