I've created CreateAccountValidator
class that is responsible for validating my binding model inside WebAPI2 application hosted on IIS.
Below is my class:
public class CreateAccountValidator : AbstractValidator<CreateAccountBindingModel>
{
public CreateAccountValidator()
{
RuleFor(u => u.Amount)
.Cascade(CascadeMode.StopOnFirstFailure)
.GreaterThan(0).WithMessage("Must be greater than 0");
RuleFor(u => u.FirstName)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("Name is required")
.Length(3, 20).WithMessage("Name must be between 3 and 20 characters");
RuleFor(u => u.LastName)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("Surname is required")
.Length(3, 20).WithMessage("Surname must be between 3 and 20 characters");
RuleFor(u => u.ID)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("ID is required")
.Must(ValidateId).WithMessage("ID is invalid");
}
private bool ValidateId(CreateAccountBindingModel createAccountBindingModel, string id, PropertyValidatorContext context)
{
var id_valid = IdValidator.IsValid(id);
if (!id_valid)
{
using (var db = new ApplicationDbContext())
{
//get request IP!!!
db.SaveAlert(createAccountBindingModel.UserEmail, "ID - CHECKSUM", string.Format("User entered: {0}", id), "192.100.100.100");
return false;
}
}
return true;
}
}
Inside ValidateId
method I'm calling my custom validator, if it returns false I want to log that fact to database.
I need to get Request IP, but I don't know how can I do that. I don't have IOwinContext or Request properties. Inside Api Controllers I'm calling:
Request.GetOwinContext().Get<ApplicationDbContext>()
Can I access IOwinContext from classes inside my application? Is yes then how can I do that?