简体   繁体   中英

asp.net core 2.0 validation flash sessions

When the validation fails I want to redirect back with the validation errors(Laravel like).

Laravel example of redirecting with errors:

redirect()->back()->withErrors(['email' => 'Email already exists']);

My controller:

[HttpPost]
public IActionResult ProcessLogin(LoginRequest loginRequest)
{
    if (! ModelState.IsValid)
    {
        // Redirect back to login view and display error messages.
    }

    // Login handling....
}

Does asp.net core 2.0 support this natively?
All I could find was returning the errors as json or by javascript validation.

The most typical and standard approach is the PRG (Post-Redirect-Get) pattern, which ASP.NET Core (and MVC, in general) follows. With this pattern, you redirect on success . If there's a validation issue, you simply return the view. In other words:

public IActionResult Login()
{
    return View();
}

[HttpPost]
public IActionResult Login(LoginRequest loginRequest)
{
    if (ModelState.IsValid)
    {
        // do login
        return Redirect("/some/url");
    }

    return View(loginRequest);
}

The ModelState object (which includes the list of validation errors) is available to the view naturally, without having to pass the errors in some way from one request to the other.

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