您能给我一个示例,说明如何从 Web 应用程序中使用的服务类返回验证错误。您如何看待下面的这种方法?
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 > 128 ||
string.IsNullOrWhiteSpace(password) || password.Length > 256)
{
TryAddModelError(model, "Username or password provided is incorrect.");
return false;
}
var user = this.db.Users.SingleOrDefault(u => 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);
}
}
}
使用示例:
[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 && this.membershipService.ValidateUser(
model.UserName, model.Password, modelState: ModelState))
{
FormsAuthentication.SetAuthCookie(userName, true);
return RedirectToLocal(returnUrl);
}
return View(model);
}
}