Custom validation at controller level in web api - c#

i'm stuck with a problem in a net standard 2.0 library and i really don't know how to approach it.
let's say i have a controller like this:
[Route("{action}/{Id}")]
[HttpPut]
public void UpdateUser([FromBody] UserDTO user, long id )
{
_service.UpdateUser(user, id);
}
easy, it works.
now i want to add some custom validation.
i know i can use System.ComponentModel.DataAnnotations on the DTO, but the message when there's a bad request is... bad.
i tried to use ValidationAttribute with a isValid,a FormatErrorMessage and add it to my controller like so
[MyValidation]
[Route("{action}/{Id}")]
[HttpPut]
public void UpdateUser([FromBody] UserDTO user, long id )
{
_service.UpdateUser(user, id);
}
but it never reached the MyValidation code, it just skipped it.
is there a way i can do this so that i can do all the validation i want and check it against my db and do all the stuff i need?
how can i proceed?
all the guides i found are related to .core or .mvc, things i can't use cos i'm on a net standard library
even a guide would be wonderful!
thanks to anyone who wants to help :D
My Solution!
so, after lots of research i found out that... it's not possibile to do it.
at least from what i understood/tried
i did a bit of a workaround because what i used can't be used on a net standard library, whatever, it seems net standard doesn't have this kind of stuff to work with.
i used the IActionFilter.
i created a class and inherited the filter and put in the two methods that it requires, OnActionExecuted and OnActionExecuting.
public class UserFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}
to read what it's inside the payload you can use
UserDTO model = new UserDTO();
model = context.ActionArguments["user"] as UserDTO;
where user is the "name" of your payload.
to know what it is, you can use the debugger and read what's inside context.actionArguments.
remember to use the " " between that name.
you have to cast it using the "as" keyword to your model.
now you have access to your payload and you can do your own custom validator!!!
in my case i created a list of string that will contain the string errors, validate id and throw an error if the list has at least one element.
example :
UserDTO model = new UserDTO();
List<string> CustomError = new List<string>();
model = context.ActionArguments["user"] as UserDTO;
if (model.Age == 0) //dumb control, just for the sake of the example
{
CustomError.Add("age cannot be 0!")
}
//other controls
if (CustomError.Count > 0)
{
context.Result = new BadRequestObjectResult(CustomError);
}
the last if is important! if the list you made has at least one element, it will throw a bad request (error 400) and you will get back a json with all the errors.
and on top of the controller you want to custom validate use
[HttpPost]
[TypeFilter(typeof(UserFilter))]
public IValidation<> PostUser(UserDTO user)
{
//your controller logic
}
hope it will help somebody in the future who got stucked like me, trying to custom validate data in a net standard, which it seems is impossible

You need to implement the ValidationAttribute class and then you can write your own logic and use as data annotation on your models.
Sample Implementation
public class ValidJoinDate : ValidationAttribute
{
protected override ValidationResult
IsValid(object value, ValidationContext validationContext)
{
DateTime _dateJoin = Convert.ToDateTime(value);
if (_dateJoin < DateTime.Now)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult
("Join date can not be greater than current date.");
}
}
}
And use in this way in your model properties:
public class Customer
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}"
, ApplyFormatInEditMode = true)]
[ValidJoinDate(ErrorMessage=
"Join Date can not be greater than current date")]
public DateTime JoinDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString =
"{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[ValidLastDeliveryDate(ErrorMessage =
"Last Delivery Date can not be less than Join Date")]
public DateTime LastDeliveryDate { get; set; }
}
Hope this solved your problem 👍

Related

how to change type validation error messages?

I'm using entity framework code first in an ASP MVC project, and I'd like to change the error message that appears for validation of a numeric type.
I have a property like
public decimal Amount1 { get; set; }
If I enter a non-number in the field, I get the message: The field Amount1 must be a number. How do I change that message?
For other validations, like Required I can just use the ErrorMessage parameter like: [Required(ErrorMessage = "My message...")]
Is there something similar for validating types?
Thank you.
Unfortunately Microsoft didn't expose any interfaces to change the default messages.
But if you are desperate enough to change these non friendly messages, you can do so by creating validation attribute for decimal, creating corresponding validator and finally register it with DataAnnotationsModelValidatorProvider at the application startup. Hope this helps.
UPDATE:
Sample below
Step 1: Create validation attribute
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
public class ValidDecimalAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (value == null || value.ToString().Length == 0) {
return ValidationResult.Success;
}
decimal d;
return !decimal.TryParse(value.ToString(), out d) ? new ValidationResult(ErrorMessage) : ValidationResult.Success;
}
}
Step 2: Create validator
public class ValidDecimalValidator : DataAnnotationsModelValidator<ValidDecimal>
{
public ValidDecimalValidator(ModelMetadata metadata, ControllerContext context, ValidDecimal attribute)
: base(metadata, context, attribute)
{
if (!attribute.IsValid(context.HttpContext.Request.Form[metadata.PropertyName]))
{
var propertyName = metadata.PropertyName;
context.Controller.ViewData.ModelState[propertyName].Errors.Clear();
context.Controller.ViewData.ModelState[propertyName].Errors.Add(attribute.ErrorMessage);
}
}
}
Step 3: Register the adapter in Global.asax under Application_Start() method or Main() method
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidDecimal), typeof(ValidDecimalValidator));
Step 4: Finally decorate your property in your model with this attribute
[ValidDecimal(ErrorMessage = "Only decimal numbers allowed")]
public decimal CPEHours { get; set; }
Hope it helps.
I couldn't find a clean solution. If there is something like [Required] you could override it in the same way. Only option I find is to remove and add another error into the model state. Again NOT the best option if you have better alternates, but does the job. This example only works if you have something like must be a number at the end. You can create a filter with this kind of loop:
foreach (var m in ModelState)
{
var errors = m.Value.Errors;
foreach (var error in errors)
{
if (error.ErrorMessage.EndsWith("must be a number"))
{
errors.Remove(error);
ModelState.AddModelError(m.Key, $"This is my own validation");
}
}
}
While it's not possible to change the whole message, you can at least change the string used to reference the field. Use the [Display(Name = "amount field"] attribute, like:
[BindProperty]
[Display(Name = "line length")]
public decimal? LineLength { get; set; }
If the user enters a string into a field like this, they will at least see an error message that reads "The value 'sdf' is not valid for line length."
Not a complete solution, but good enough in many scenarios.

Is it possible to use Web API model validation on query parameters?

I am currently trying to write a Web API application where one of the parameters I'd like to validate is a query parameter (that is, I wish to pass it in in the form /route?offset=0&limit=100):
[HttpGet]
public async Task<HttpResponseMessage> GetItems(
int offset = 0,
int limit = 100)
{
if (!ModelState.IsValid)
{
// Handle error
}
// Handle request
}
In particular, I want to ensure that "offset" is greater than 0, since a negative number will cause the database to throw an exception.
I went straight for the logical approach of attaching a ValidationAttribute to it:
[HttpGet]
public async Task<HttpResponseMessage> GetItems(
[Range(0, int.MaxValue)] int offset = 0,
int limit = 100)
{
if (!ModelState.IsValid)
{
// Handle error
}
// Handle request
}
This does not cause any errors at all.
After a lot of painful debugging into ASP.NET, it appears to me that this may be simply impossible. In particular, because the offset parameter is a method parameter rather than a field, the ModelMetadata is created using GetMetadataForType rather than GetMetadataForProperty, which means that the PropertyName will be null. In turn, this means that AssociatedValidatorProvider calls GetValidatorsForType, which uses an empty list of attributes even though the parameter had attributes on it.
I don't even see a way to write a custom ModelValidatorProvider in such a way as to get at that information, because the information that this was a function parameter seems to have been lost long ago. One way to do that might be to derive from the ModelMetadata class and use a custom ModelMetadataProvider as well but there's basically no documentation for any of this code so it would be a crapshoot that it actually works correctly, and I'd have to duplicate all of the DataAnnotationsModelValidatorProvider logic.
Can someone prove me wrong? Can someone show me how to get validation to work on a parameter, similar to how the BindAttribute works in MVC? Or is there an alternative way to bind query parameters that will allow the validation to work correctly?
You can create a view request model class with those 2 properties and apply your validation attributes on the properties.
public class Req
{
[Range(1, Int32.MaxValue, ErrorMessage = "Enter number greater than 1 ")]
public int Offset { set; get; }
public int Limit { set; get; }
}
And in your method, use this as the parameter
public HttpResponseMessage Post(Req model)
{
if (!ModelState.IsValid)
{
// to do :return something. May be the validation errors?
var errors = new List<string>();
foreach (var modelStateVal in ModelState.Values.Select(d => d.Errors))
{
errors.AddRange(modelStateVal.Select(error => error.ErrorMessage));
}
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Error",
Errors = errors });
}
// Model validation passed. Use model.Offset and Model.Limit as needed
return Request.CreateResponse(HttpStatusCode.OK);
}
When a request comes, the default model binder will map the request params(limit and offset, assuming they are part of the request) to an object of Req class and you will be able to call ModelState.IsValid method.
For .Net 5.0 and validating query parameters:
using System.ComponentModel.DataAnnotations;
namespace XXApi.Models
{
public class LoginModel
{
[Required]
public string username { get; set; }
public string password { get; set; }
}
}
namespace XXApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
[HttpGet]
public ActionResult login([FromQuery] LoginModel model)
{
//.Net automatically validates model from the URL string
//and gets here after validation succeeded
}
}
}
if (Offset < 1)
ModelState.AddModelError(string.Empty, "Enter number greater than 1");
if (ModelState.IsValid)
{
}

asp.net mvc modelbinding for username and date

I have a logging controller in my project that gets Log data from javascript client side and sends to server.
Log Model ils like this.
public class Log
{
public string Event { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public string Username { get; set; }
}
My controller action is like this.
[HttpPost]
public JsonResult Save(Log log)
{
log.Username = User.Identity.Name;
log.Date = DateTime.now;
return Json(new { message = "ok" }, JsonRequestBehavior.AllowGet);
}
when users sended the log data, I need to set the username and date. Is there another way with model binding or else? Automatically set the context.username and date time of log.
IModelBinder is the preferred way to go. You implement the interface and register it in Global.asax file
ModelBinders.Binders.Add(typeof(Log), new LogModelBinder());
What I don't like about this approach is that you have to be aware that there is a custom model binder for this type implemented somewhere and it can cause confusion if you forget about it, or you have a new developer working on the project and model starts behaving strange. It is just not obvious enough what is changing the object.
I like to have all my custom logic implemented in the controller itself. You can override OnActionExecuting and inject the properties there, better yet, have a BaseController that all your controllers inherit from and do your custom logic in there.
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
object model = filterContext.ActionParameters
.TryGetValue("model", out model)
? model : null;
if (model != null)
{
var logModel = model as Log;
if (logModel != null)
{
logModel.Date = DateTime.Now;
logModel.Username = filterContext.HttpContext.User.Identity.Name;
}
}
}

Domain object to ViewModel & vice versa using Automapper

I'm developing a new MVC site for my company & kind of confused as how to create mapping from Domain/POCO objects to ViewModel classes [contains validation] & vice versa. Here's an sample example.
My domain class [just to keep it simple I'hv omitted other properties]:
public partial class Glossary
{
public int Id { get; set; }
public string GlossaryItem { get; set; }
public string Definition { get; set; }
}
my ViewModel class inside my MVC app's model folder [with corrosponding validation]:
public class GlossaryModel
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a GlossaryItem")]
public string GlossaryItem { get; set; }
[Required(ErrorMessage = "Please enter a Definition")]
public string Definition { get; set; }
}
my Automapper configuration for DTO to Domain Model:
protected override void Configure()
{
CreateMap<GlossaryModel, Glossary>();
//....... etc
}
My controller's action method for editing an item:
public class GlossaryController : Controller
{
IGlossaryRepository _glossaryRepository;
IMappingService _mappingService;
public GlossaryController(IGlossaryRepository glossaryRepository, IMappingService autoMapperMappingService)
{
_glossaryRepository = glossaryRepository;
_mappingService = autoMapperMappingService;
}
// .... etc
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Edit(GlossaryModel glossaryModel)
{
if (ModelState.IsValid)
{
var glossary = _mappingService.Map<GlossaryModel, Glossary>(glossaryModel);
if (glossaryModel.Id <= 0)
_glossaryRepository.Add(glossary);
else
_glossaryRepository.Edit(glossary);
_glossaryRepository.Save();
TempData["message"] = string.Format("{0} has been saved", glossaryModel.Definition);
return RedirectToAction("All");
}
return View(glossaryModel);
}
//....etc
}
And it's working fine, but my question is... Now say I need an action that will list down all glossary items like..
public ActionResult All()
{
var allItems = _glossaryRepository.Glossary;
if (allItems.Count() == 0) return View(new List<GlossaryModel>());
// **The below line is the reverse mapping one**
var allItemsModel = _mappingService.Map<IEnumerable<Glossary>, IEnumerable<GlossaryModel>>(allItems);
return View(allItemsModel);
}
But now I need automapper to convert from Domain objects to DTO [from List(Glossary) to List(GlossaryModel)], just opposite of the Edit method, to push the data to the view. So do I again need to map the opposite binding in the automapper config...!! like
protected override void Configure()
{
CreateMap<GlossaryModel, Glossary>(); // Added before for DTO to Domain object
CreateMap<Glossary, GlossaryModel>();// Added for Domain object to DTO
//....... etc
}
Is it a good design to bind both ways? or there's better solution I'm missing, Please help
Thanks,
Sanjay
Jimmy Bogard also asked the same question. But there was enough demand for it that direct support has been added for simple cases like you've listed. In fact, in this answer Jimmy also suggested that there's nothing wrong with it if it works for you. A simple example is:
protected override void Configure()
{
CreateMap<GlossaryModel, Glossary>()
.ReverseMap();
//....... etc
}
Note that ReverseMap doesn't work for more complex mappings. See this answer for more details.
Automapper was build to Domain to ViewModel (Domain to DTO in the manner in which you've described it) mapping
Summed up well by #Marius' answer here What is wrong with two-way mapping?
In some medium sized projects I've used two way mapping and for larger projects I use Domain To View Model mapping and then used a CQRS system for sending the ViewModel values to the underlying persistence store.
When it comes down to it, it is up to you how you choose to use Automapper and what Architectural decisions make sense to you.
The world will not stop rotating if you do 2 way mapping.

Validation of Guid

I have a strongly-typed view which has a DropDownListFor attribute on it.
Each item in the dropdown list is represented by a GUID.
What I'm after is a way to validate if a user selects an item from the dropdown list. At present i don't see anyway of doing this using Data Annotations.
Is there anyway of achieving this using Data Annotations so client and server side validation would work.
I'm guessing i need to make a custom method to do this but was wondering if anything already existed.
Actually, you can't use Required attribute with GUIDs (without the method I mention below) because they inherit from struct, and as such their default value is actually an instance of Guid.Empty, which will satisfy the requirements of the Required attribute. Now that being said, it is possible to get what you want you just need to make your property nullable, take this for example...
public class Person
{
[Required] //Only works because the Guid is nullable
public Guid? PersonId { get; set;}
public string FirstName { get; set;}
public string LastName { get; set;}
}
By marking the GUID nullable (using the ?, or Nullable if you prefer the long way) you let it stay as null when binding against what the browser sent. In your case, just make sure the value of the default option of the dropdown uses an empty string as it's value.
EDIT: The only caveat to this method is you end up having to use something like Person.GetValueOfDefault() everywhere and potentially testing for Guid.Empty. I got tired of doing this and ended up creating my own validation attribute to help simplify validating Guids (and any other types that have default values I want to treat as invalid such as int, DateTime, etc). However I don't have client side validation to go along with this yet, so validation only happens on the server. This can be combined with [Required] (designed to not duplicate functionality of [Required]) if you're ok with using nullable types. This would mean you still have to use GetValueOrDefault(), but at least then you don't have to test for Guid.Empty anymore. The Gist link has some XMLDocs with examples, I left them out here for brevity. I'm currently using it with ASP.NET Core.
EDIT: Updated to fix a bug with Nullable<>, and a bug with treating null as invalid. Added supporting classes to handle client side validation. See Gist for full code.
Gist: RequireNonDefaultAttribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RequireNonDefaultAttribute : ValidationAttribute
{
public RequireNonDefaultAttribute()
: base("The {0} field requires a non-default value.")
{
}
public override bool IsValid(object value)
{
if (value is null)
return true; //You can flip this if you want. I wanted leave the responsability of null to RequiredAttribute
var type = value.GetType();
return !Equals(value, Activator.CreateInstance(Nullable.GetUnderlyingType(type) ?? type));
}
}
Edited Answer
Upon re-reading your question, it sounds like you just want to know if a value is selected. If that's the case then just apply the RequiredAttribute to the Guid property and make it nullable on the model
public class GuidModel
{
[Required]
public Guid? Guid { get; set; }
public IEnumerable<Guid> Guids { get; set; }
}
then in the strongly typed View (with #model GuidModel)
#Html.ValidationMessageFor(m => m.Guid)
#Html.DropDownListFor(
m => m.Guid,
Model.Guids.Select(g => new SelectListItem {Text = g.ToString(), Value = g.ToString()}),
"-- Select Guid --")
Add the client validation JavaScript script references for client-side validation.
The controller looks like
public class GuidsController : Controller
{
public GuidRepository GuidRepo { get; private set; }
public GuidsController(GuidRepository guidRepo)
{
GuidRepo = guidRepo;
}
[HttpGet]
public ActionResult Edit(int id)
{
var guid = GuidRepo.GetForId(id);
var guids - GuidRepo.All();
return View(new GuidModel { Guid = guid, Guids = guids });
}
[HttpPost]
public ActionResult Edit(GuidModel model)
{
if (!ModelState.IsValid)
{
model.Guids = GuidRepo.All();
return View(model);
}
/* update db */
return RedirectToAction("Edit");
}
}
This will ensure that the Guid property is required for a model-bound GuidModel.
Original Answer
I don't believe that there is a ready made Data Annotation Validation attribute that is capable of doing this. I wrote a blog post about one way to achieve this; the post is using an IoC container but you could take the hard coded dependency if you're wanting to get something working.
Something like
public class ValidGuidAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "'{0}' does not contain a valid guid";
public ValidGuidAttribute() : base(DefaultErrorMessage)
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var input = Convert.ToString(value, CultureInfo.CurrentCulture);
// let the Required attribute take care of this validation
if (string.IsNullOrWhiteSpace(input))
{
return null;
}
// get all of your guids (assume a repo is being used)
var guids = new GuidRepository().AllGuids();
Guid guid;
if (!Guid.TryParse(input, out guid))
{
// not a validstring representation of a guid
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
// is the passed guid one we know about?
return guids.Any(g => g == guid) ?
new ValidationResult(FormatErrorMessage(validationContext.DisplayName)) : null;
}
}
and then on the model you send into the controller action
public class GuidModel
{
[ValidGuid]
public Guid guid { get; set; }
}
This gives you server side validation. You could write client side validation to do this as well, perhaps using RemoteAttribute but I don't see a lot of value in this case as the only people that are going to see this client side validation are people that are messing with values in the DOM; it would be of no benefit to your normal user.
I know this is an old question now, but if anyone else is interested I managed to get around this by creating an [IsNotEmpty] annotation (making the Guid nullable wasn't an option in my case).
This uses reflection to work out whether there's an implementation of Empty on the property, and if so compares it.
public class IsNotEmptyAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) return false;
var valueType = value.GetType();
var emptyField = valueType.GetField("Empty");
if (emptyField == null) return true;
var emptyValue = emptyField.GetValue(null);
return !value.Equals(emptyValue);
}
}
Regex actually does work (if you use the right one!)
[Required]
[RegularExpression("^((?!00000000-0000-0000-0000-000000000000).)*$", ErrorMessage = "Cannot use default Guid")]
public Guid Id { get; set; }
Non Empty Guid Validator
prevents 00000000-0000-0000-0000-000000000000
Attribute:
using System.ComponentModel.DataAnnotations;
[AttributeUsage(AttributeTargets.Property)]
internal class NonEmptyGuidAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if ((value is Guid) && Guid.Empty == (Guid)value)
{
return new ValidationResult("Guid cannot be empty.");
}
return null;
}
}
Model:
using System.ComponentModel.DataAnnotations;
public class Material
{
[Required]
[NonEmptyGuid]
public Guid Guid { get; set; }
}
If the custom validation doesn't require a high reuse in your system (i.e. without the need for a custom validation attribute), there's another way to add custom validation to a ViewModel / Posted data model, viz by using IValidatableObject.
Each error can be bound to one or more model properties, so this approach still works with e.g. Unobtrusive validation in MVC Razor.
Here's how to check a Guid for default (C# 7.1):
public class MyModel : IValidatableObject // Implement IValidatableObject
{
[Required]
public string Name {get; set;}
public Guid SomeGuid {get; set;}
... other properties here
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (SomeGuid == default)
{
yield return new ValidationResult(
"SomeGuid must be provided",
new[] { nameof(SomeGuid) });
}
}
}
More on IValidatableObject here
You can validate the Guid if it contains default values - "00000000-0000-0000-0000-000000000000".
if (model.Id == Guid.Empty)
{
// TODO: handle the error or do something else
}
You can create a custom validator for that.
using System;
using System.ComponentModel.DataAnnotations;
namespace {{Your_App_Name}}.Pages
{
public class NotEmptyGuidAttribute: ValidationAttribute
{
protected override ValidationResult IsValid(object guidValue, ValidationContext validationContext)
{
var emptyGuid = new Guid();
var guid = new Guid(guidValue.ToString());
if (guid != emptyGuid){
return null;
}
return new ValidationResult(ErrorMessage, new[] {validationContext.MemberName});
}
}
}
You can use it like this
[EmptyGuidValidator(ErrorMessage = "Role is required.")]
public Guid MyGuid{ get; set; }
This worked for me.

Categories

Resources