Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to return validation errors from service class methods?
    primarykey
    data
    text
    <p>Can you give me an example of how to return validation errors from a service class used in a web application. What do you think about this approach below?</p> <pre><code>using System; using System.Linq; using System.Web.Mvc; using App.Data; using App.Security; public interface IMembershipService { bool ValidateUser(string userName, string password, ModelStateDictionary model = null); } public class MembershipService : IMembershipService { private DatabaseContext db; public MembershipService(DatabaseContext db) { this.db = db; } public bool ValidateUser(string userName, string password, ModelStateDictionary model) { if (string.IsNullOrWhiteSpace(userName) || userName.Length &gt; 128 || string.IsNullOrWhiteSpace(password) || password.Length &gt; 256) { TryAddModelError(model, "Username or password provided is incorrect."); return false; } var user = this.db.Users.SingleOrDefault(u =&gt; u.UserName == userName); if (user == null || !PasswordHash.Validate(password, user.PasswordHash, user.PasswordSalt)) { TryAddModelError(model, "Username or password provided is incorrect."); return false; } if (!user.IsApproved) { TryAddModelError(model, "Your account is suspended."); return false; } user.LastLoginDate = DateTime.UtcNow; this.db.SaveChanges(); return true; } private static void TryAddModelError(ModelStateDictionary model, string errorMessage) { if (model != null) { model.AddModelError(string.Empty, errorMessage); } } } </code></pre> <p>Usage sample:</p> <pre><code>[Authorize] public class AccountController : Controller { private readonly IMembershipService membershipService; public AccountController(IMembershipService membershipService) { this.membershipService = membershipService; } [HttpPost, AllowAnonymous, ValidateAntiForgeryToken] public Login(LoginModel model, string returnUrl) { if (ModelState.IsValid &amp;&amp; this.membershipService.ValidateUser( model.UserName, model.Password, modelState: ModelState)) { FormsAuthentication.SetAuthCookie(userName, true); return RedirectToLocal(returnUrl); } return View(model); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload