简体   繁体   中英

Redirect to Angular route after logging with ASP.NET MVC 5

I am using asp.net mvc 5 application logging with the following loging action in AccountController:

 // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { ## not working, just a trial ##returnUrl = "Dashboard#!/requests"; if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change >to shouldLockout: true var result = await > >SignInManager.PasswordSignInAsync(model.UserName, model.Password,

model.RememberMe, shouldLockout: false);

 switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } }

and with this form:

<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.UserName, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.UserName, "", 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>

After user login, I want a user to redirect to url "Dashboard#!/requests" where Dashboard is ASP.NET MVC 5 Controller and /requests is Angular route using HTML5 and ! prefix:

 $locationProvider.html5Mode(false).hashPrefix('!'); // This is for Hashbang Mode

app.config(function ($routeProvider, $locationProvider) { $routeProvider

 .when('/requests', { templateUrl: '/Template/Request/Index.html', controller: 'requestsController' }) .when('/request/:wf/:requestId', { templateUrl: function(params) { return '/Template/Request/' + params.wf + '/Open.html'; }, controller: 'requestsController' }); $locationProvider.html5Mode(false).hashPrefix('!'); // This is for Hashbang Mode });

How to redirect a user into the url combined with asp.net mvc 5 controller and angular?

You can do it, you just need to organize your RouteConfig.cs file. Direct the user to the Index method of the Home Controller but also delete all the code in the Home Index View. Within your layout add the app-root and you will want to do something like the following.

    @if (User.Identity.IsAuthenticated)
    {
        <app-root></app-root>
    }
    @RenderBody()

Next you need to set up the RouteConfig.cs file to handle this. You will want to do something like the following

        routes.MapRoute(
            name: "logout",
            url: "Account/Logoff",
            defaults: new { controller="Account", action = "Logoff", id = 
            UrlParameter.Optional}
            );

        routes.MapRoute(
            name: "login",
            url: "Account/Login",
            defaults: new { controller = "Account", action = "Login", id = 
            UrlParameter.Optional }
            );

        routes.MapRoute(
          name: "register",
          url: "Account/Register",
          defaults: new { controller = "Account", action = "Register", id = 
          UrlParameter.Optional }
          );

         routes.MapRoute(
            name: "Angular",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index"}
            );

This will keep Asp.Net in charge of login, logout, and registering the users.

Finally you need to set up the app-routing-module.ts file. Just set the path to what component you want the user to reach after the login. This is going to be the base address or the "home" address.

import { HomeComponent } from '{path to home component}';

const routes: Routes = [
  { path: '', component: HomeComponent }
];

This will cause the user to reach the angular aspect of your application after they login.

Hope this helps someone.

I think no way...

After search and search ... I think not possible (easily), the last part of url don't arrive to the server.

I think the solution is use html5Mode(true) in this article show how: http://www.jlum.ws/post/2014/10/10/handling-routes-between-an-angularjs-application-and-aspnet-mvc-application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM