Я новичок в Asp.Net MVC, так что извините, если он выглядит тривиальным.RedirectToAction MVC5 не работает
Я следую за этот учебник: http://techbrij.com/custom-roleprovider-authorization-asp-net-mvc
У меня есть проблема с RedirectToAction
метод, я звоню это после моего входа в действие так:
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
using (AferSuiviDBEntities objContext = new AferSuiviDBEntities())
{
var objUser = objContext.People.FirstOrDefault(x => x.CompanyMail == model.Email && x.CompanyPassword == model.Password);
if (objUser == null)
{
ModelState.AddModelError("LogOnError", "The user name or password provided is incorrect.");
}
else
{
FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
Session["MyMenu"] = null;
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("RedirectToDefault");
}
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Я написал RedirectToDefault
метод, который проверяет, вошедшего пользователя и показывать по странице:
public ActionResult RedirectToDefault()
{
String[] roles = Roles.GetRolesForUser();
if (roles.Contains("Administrator"))
{
return RedirectToAction("Index", "Home");
}
else if (roles.Contains("Engineer"))
{
return RedirectToAction("Index", "Engineer");
}
else if (roles.Contains("PublicUser"))
{
return RedirectToAction("Index", "PublicUser");
}
else
{
return RedirectToAction("Index");
}
}
Мои routeConfigfile является следующее:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
}
}
Проблема заключается в том, что, когда я настройки учетных данных, а затем нажмите кнопку «Вход» кнопка, это происходит из этого URL:
http://localhost:3343/Account/Login
к этому:
http://localhost:3343/Account/Login?ReturnUrl=%2FAccount%2FRedirectToDefault
В страница регистрации еще отображается! может кто-нибудь объяснить мне, почему, пожалуйста?
PS: Я поставил точку останова в методе RedirectToDefault, и я увидел, что он не входит внутрь!
UPDATE
Мое мнение Логин:
@model LoginViewModel
@{
ViewBag.Title = "Log in";
}
<h2>@ViewBag.Title.</h2>
<div class="row">
<div class="col-md-8">
<section id="loginForm">
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<p>
@Html.ActionLink("Register as a new user", "Register")
</p>
@* Enable this once you have account confirmation enabled for password reset functionality
<p>
@Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>*@
}
</section>
</div>
<div class="col-md-4">
<section id="socialLoginForm">
@Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
</section>
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
UPDATE 2
Вот изображение моего кода, он показывает, что процесс действительно будет мой метод RedirectToAction:
Но при нажатии на F11 он не входит в мой метод «RedirectToDefault», он заканчивается, но он просто обновляет мой первый вход в систему.
Что такое 'action' атрибут' '
Где ваш метод 'RedirectToDefault' - в том же контроллере? Если вы поставили точку останова в строке 'FormsAuthentication.SetAuthCookie (model.Email, model.RememberMe)', является ли 'RedirectToDefault' даже вызванным? –
@StephenMuecke Я обновляю сообщение для вас – NTinkicht