Currently, I have an ASP.NET Web Api running side by side with an ASP.NET web application. Using the methodology outlined by Yao Huang in his blog posts relating to the HelpPage NuGet package, specifically XMLDocumentationProvider, I have successfully been able to document my API - almost...
The problem that I am running into is that particular API method calls inherit (and possibly override) the behavior from a base class, we'll call it ApiBase. As a result, these methods do not have their own documentation, as they are inheriting the method from the base class and usually need no further explanation than that provided by ApiBase. What I'm trying to do (and have no direction as to how to do it) is, for methods that inherit implementation from a base class, find a way to inherit and display the associated XML comments associated with the base class and display them with the method being invoked.
To clarify this, here is a sample method from ApiBase:
public abstract class ApiBase
{
/// <summary>
/// Stub used as an example
/// </summary>
/// <param name="stub">Random boolean value</param>
/// <returns>The boolean value</returns>
public virtual bool returnBool(bool stub)
{
return stub;
}
/// <summary>
/// Stub #2 used as an example
/// </summary>
/// <param name="stub">Random int value</param>
/// <returns>A value less than the parameter</returns>
public virtual int returnLess(int stub)
{
return (stub - 10);
}
}
Later on, let's say we have a controller class, ApiChild, that inherits this functionality:
public class ApiChild : ApiBase
{
public override int returnLess(int stub)
{
return (stub - 20);
}
}
When ApiChild invokes either returnBool or returnLess, I'd like their comments to be grabbed from the base class by XMLDocumentationProvider. ApiExplorer already grabs the rest of the information, such as return type, parameters, etc., successfully from the base class, but I am unsure as to how to extend this functionality to comment retrieval. I appreciate any help you may be able to provide. My own thoughts lean toward some sort of implementation that uses reflection to analyze a method during run time to determine its attributes and somehow appropriately grab comments from its parent if need be. Any thoughts/guidance is much appreciated.
For reference, here is the current code used in XMLDocumentationProvider:
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using System.Xml.XPath;
namespace MyProject.Areas.HelpPage
{
public interface IResponseDocumentationProvider
{
string GetResponseDocumentation(HttpActionDescriptor actionDescriptor);
}
/// <summary>
/// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file.
/// </summary>
public class XmlDocumentationProvider : IDocumentationProvider, IResponseDocumentationProvider
{
private XPathNavigator _documentNavigator;
private const string MethodExpression = "/doc/members/member[#name='M:{0}']";
private const string ParameterExpression = "param[#name='{0}']";
/// <summary>
/// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
/// </summary>
/// <param name="documentPath">The physical path to XML document.</param>
public XmlDocumentationProvider(string documentPath)
{
if (documentPath == null)
{
throw new ArgumentNullException("documentPath");
}
XPathDocument xpath = new XPathDocument(documentPath);
_documentNavigator = xpath.CreateNavigator();
}
public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
if (methodNode != null)
{
XPathNavigator summaryNode = methodNode.SelectSingleNode("summary");
if (summaryNode != null)
{
return summaryNode.Value.Trim();
}
}
return null;
}
public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
if (reflectedParameterDescriptor != null)
{
XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
if (methodNode != null)
{
string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
if (parameterNode != null)
{
return parameterNode.Value.Trim();
}
}
}
return null;
}
private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)
{
ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
if (reflectedActionDescriptor != null)
{
string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));
return _documentNavigator.SelectSingleNode(selectExpression);
}
return null;
}
private static string GetMemberName(MethodInfo method)
{
string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", method.DeclaringType.FullName, method.Name);
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 0)
{
string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();
name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames));
}
return name;
}
private static string GetTypeName(Type type)
{
if (type.IsGenericType)
{
// Format the generic type name to something like: Generic{System.Int32,System.String}
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string typeName = genericType.FullName;
// Trim the generic parameter counts from the name
typeName = typeName.Substring(0, typeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
return String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", typeName, String.Join(",", argumentTypeNames));
}
return type.FullName;
}
public virtual string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
if (methodNode != null)
{
XPathNavigator returnsNode = methodNode.SelectSingleNode("returns");
if (returnsNode != null)
return returnsNode.Value.Trim();
}
return null;
}
}
}
Related
I am currently working with MVC4 data annotations to handle validation. I am working on a site that will be very much international and as such I keep all of my text in resource files.
I also want to keep regular expressions for validation in resource files so I can use the same code to check, for example, Post Codes (UK) and Zip Codes (US) just by using a different RegEx (and resources for the different names etc).
I have the below attribute which is already pulling the error message from a resource file. How can I have it get the regex from a resource file too?
[RegularExpression(#"^[\w]{1,2}[0-9]{1,2}[\w]?\s?[0-9]{1,2}[\w]{1,2}$", ErrorMessageResourceType = typeof(Resources.ValidationMessages), ErrorMessageResourceName = "validPostcode")]
EDIT (AGAIN)
Where I am now
Following the answer below and some additional searching around, I have the following:
In Global.asax.cs I have added the below line to ensure client side validation is invoked
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalisedAttribute), typeof(RegularExpressionAttributeAdapter));
In my model, I have this call to the attribute extension
[Localised(typeof(Resources.FormValidation), "postcodeRegEx", "postcodeMsg")]
And finally, the attribute extension for localised regex validation
public class LocalisedAttribute : RegularExpressionAttribute
{
public LocalisedAttribute(Type resource, string regularExpression, string errorMessage)
: base(GetRegex(regularExpression))
{
ErrorMessageResourceType = resource;
ErrorMessageResourceName = errorMessage;
}
private static string GetRegex(string value)
{
return Resources.FormValidation.ResourceManager.GetString(value);
}
}
This works, but ONLY the first time I use it when starting the application.
I am going to open another question to get around that problem - it's not directly related to the original request, doesn't seem to be relevant to most peoples implementation and doesn't seem to be specific to data annotations.
I already have some extended kind of RegularExpressionAttribute implementation, that allows to use resources for regex pattern. It looks like:
public class RegularExpressionExAttribute : RegularExpressionAttribute, IClientValidatable
{
private Regex regex { get; set; }
private string pattern;
private string resourceName;
private Type resourceType;
/// <summary>
/// constructor, calls base with ".*" basic regex
/// </summary>
/// <param name="resName">resource key</param>
/// <param name="resType">resource type</param>
public RegularExpressionExAttribute(string resName, Type resType)
: base(".*")
{
resourceName = resName;
resourceType = resType;
}
/// <summary>
/// override RegularExpressionAttribute property
/// </summary>
public new string Pattern
{
get
{
SetupRegex();
return pattern;
}
}
/// <summary>
/// loads regex from resources
/// </summary>
private void SetupRegex()
{
ResourceAccessor ra = new ResourceAccessor(resourceName, resourceType);
pattern = ra.resourceValue;
regex = new Regex(pattern);
}
/// <summary>
/// override validation with our regex
/// </summary>
/// <param name="value">string for validation</param>
/// <returns></returns>
public override bool IsValid(object value)
{
SetupRegex();
string val = Convert.ToString(value);
if (string.IsNullOrEmpty(val))
return true;
var m = regex.Match(val);
return (m.Success && (m.Index == 0));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metaData, ControllerContext controllerContext)
{
yield return new ModelClientValidationRegexRule(base.ErrorMessageString, this.Pattern);
}
}
Also it's using ResourceAccessor class to get regex out of resources
public class ResourceAccessor
{
private string resourceName;
private Type resourceType;
private Func<string> accessor;
private string _resourceValue;
public ResourceAccessor(string resourceName, Type resourceType)
{
this.resourceName = resourceName;
this.resourceType = resourceType;
}
public string resourceValue
{
get
{
SetupAccessor();
return accessor();
}
}
private void SetupAccessor()
{
if (accessor != null) //already set
return;
string localValue = _resourceValue;
bool flag1 = !string.IsNullOrEmpty(resourceName);
bool flag2 = !string.IsNullOrEmpty(localValue);
bool flag3 = resourceType != (Type)null;
if (flag1 == flag2)
{
throw new InvalidOperationException("Can't set resource value");
}
if (flag3 != flag1)
{
throw new InvalidOperationException("Resource name and type required");
}
if (flag1)
PropertyLookup();
else
{
accessor = (Func<string>)(() => localValue);
}
}
private void PropertyLookup()
{
if (resourceType == (Type)null || string.IsNullOrEmpty(resourceName))
{
throw new InvalidOperationException("Resource name and type required");
}
PropertyInfo property = resourceType.GetProperty(resourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (property != (PropertyInfo)null)
{
MethodInfo getMethod = property.GetGetMethod(true);
if (getMethod == (MethodInfo)null || !getMethod.IsAssembly && !getMethod.IsPublic)
property = (PropertyInfo)null;
}
if (property == (PropertyInfo)null)
{
throw new InvalidOperationException("Resource type doesn't have property");
}
else if (property.PropertyType != typeof(string))
{
throw new InvalidOperationException("Resource type must be string");
}
else
{
accessor = (Func<string>)(() => (string)property.GetValue((object)null, (object[])null));
}
}
}
And here is usage samples:
public class SignUpInput
{
[RegularExpressionEx("EmailValidationRegex", typeof(LocalizedResources), ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "invalidEmail")]
public string Email { get; set; }
}
I think yuo can extend RegularExpressionAttribute
public class PostCodeValidationAttribute : RegularExpressionAttribute
{
public PostCodeValidationAttribute()
: base(Resources.PostCodeValidationExpression)
{
}
}
UPDATE
Put culture info name in session for example accordingly with user choice. And use it in
ResourceManager.GetString(value, CultureInfo.CreateSpecificCulture(userCulture));
At first you can test it with hardcode value. Something like this
ResourceManager.GetString(value, CultureInfo.CreateSpecificCulture("en-GB"));
instead
ResourceManager.GetString(value, CultureInfo.CreateSpecificCulture(currentCulture));
or in base constructor
base(GetRegex(regularExpression, ""en-GB""))
The goal of the function is to fill the from (from 3rd party website) and click the submit button and gets the html source of the submitted result page. This task needs to be done on click event of the button in asp.net. If the function returns true, do some sql tasks at the end. I read about the Asynchronous Handler in asp.net but really beginner of that and not sure what a best solution is to simulate this type of task in asp.net.
Protected Sub lbtnSave_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles lbtnSave.Click
If CrawlWebSite() then
'Save
End If
End Sub
Private Function CrawlWebSite() As Boolean
Dim objBrowser = CreateObject("InternetExplorer.Application")
Dim url As String = "https://test.com/Search.do?subAction=reset&searchType=ind"
With objBrowser
.navigate(url)
System.Threading.Thread.Sleep(1000)
Dim StartTime As DateTime
Dim ElapsedTime As TimeSpan
Dim bLong As Boolean = False
StartTime = Now
Do While .busy = True
ElapsedTime = Now().Subtract(StartTime)
If (ElapsedTime.TotalSeconds Mod 60) >= 55 Then
bLong = True
Exit Do
End If
System.Threading.Thread.Sleep(1000)
Loop
If bLong = True Then
PageName.Alert(Page, "There is a delay retrieving the website for checking NPI. Please try again.")
Return False
End If
.document.getElementById("lastname").Value = txtLastName.Text.Trim
.document.getElementById("searchNpi").Value = txtUPIN.Text.Trim
.document.getElementsByTagName("input").item(7).click()
System.Threading.Thread.Sleep(1000)
bLong = False
StartTime = Now
Do While .busy = True
'There is a delay retrieving the website. Continue ?
ElapsedTime = Now().Subtract(StartTime)
If (ElapsedTime.TotalSeconds Mod 60) >= 50 Then
bLong = True
Exit Do
End If
System.Threading.Thread.Sleep(1000)
Loop
If bLong = True Then
PageName.Alert(Page, "There is a delay retrieving the website. Please try again.")
Return False
End If
If .document.getElementById("lastname") Is Nothing Then
'We have result
Return True
Else
PageName.Alert(Page, "Attention: No matching records found.")
Return False
End If
End With
End Function
Here are some classes used in implementing long-polling using HttpHandlers. I use this solution for operations that take a LONG time to finish. There are basically 6 classes (see below). Some of these classes may end-up being unneeded for YOUR purposes, but they made sense for mine. These have "mostly" been sanitized for you.
Controller: Processes actions required to create a valid response (db operations etc.)
Processor: Manages asynch communication with the web page (itself)
IAsynchProcessor: The service processes instances that implement this interface
Sevice: Processes request objects that implement IAsynchProcessor
Request: The IAsynchProcessor wrapper containing your response (object)
Response: Contains custom objects or fields
If you need help with the JavaScript or HTML add-in a comment below...I will write something for you.
HTTP HANDLERS:
using System;
using System.Configuration;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.SessionState;
namespace Concept.LongPolling.Handlers
{
/// <summary>
/// Summary description for Controller
/// </summary>
public class Controller : IHttpHandler, IReadOnlySessionState
{
#region CONSTRUCTORS
#endregion
#region PROPERTIES
/// <summary>Gets a Boolean value indicating that another request can use the current instance of the DefaultHttpHandler class.</summary>
/// <remarks>Returning true makes the same AsyncHttpHandler object be used for all requests.</remarks>
/// <remarks>Returning false here makes ASP.Net create object per request.</remarks>
public bool IsReusable { get { return true; } }
#endregion
#region METHODS
/// <summary>Enables synchronous processing of HTTP Web requests</summary>
/// <param name="context">An HttpContext object that provides references to the intrinsic server objects</param>
/// /// <remarks>This is where you would send commands to the controller that would affect processing in some manner.</remarks>
public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
/// <summary>Creates the response object which is serialized back to the client</summary>
/// <param name="response"></param>
public static Response CreateResponse(Response response)
{
try
{
response.Generate();
}
catch (System.Exception ex)
{
response.SessionValid = false;
}
return response;
}
#endregion
}
}
using System;
using System.Configuration;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.SessionState;
using Concept.LongPolling.LongPolling;
namespace Concept.LongPolling.Handlers
{
/// <summary>
/// Summary description for Processor
/// </summary>
public class Processor : IHttpHandler, IHttpAsyncHandler, IReadOnlySessionState
{
#region CONSTRUCTORS
#endregion
#region PROPERTIES
/// <summary>Gets a Boolean value indicating that another request can use the current instance of the DefaultHttpHandler class.</summary>
/// <remarks>Returning true makes the same AsyncHttpHandler object be used for all requests.</remarks>
/// <remarks>Returning false here makes ASP.Net create object per request.</remarks>
public bool IsReusable { get { return false; } }
#endregion
#region METHODS
/// <summary>Enables synchronous processing of HTTP Web requests</summary>
/// <param name="context">An HttpContext object that provides references to the intrinsic server objects</param>
public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
#region IHttpAsyncHandler Members
/// <summary>Enables asynchronous processing of HTTP Web requests</summary>
/// <param name="context">An HttpContext object that provides references to the intrinsic server objects</param>
/// <param name="cb">The method to call when the asynchronous method call is complete. If callback is null, the delegate is not called.</param>
/// <param name="extraData"></param>
/// <returns>Any state data that is needed to process the request.</returns>
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
Int32 someValueYouLikeToSendInYourClass = Convert.ToInt32(context.Request["Number"]);
Request request = new Request(cb, context);
request.Response.Number = someValueYouLikeToSendInYourClass;
Service.Singleton.AddRequest(request);
return request;
}
/// <summary>Provides an end method for an asynchronous process.</summary>
/// <param name="result">An object that contains information about the status of the process.</param>
public void EndProcessRequest(IAsyncResult result)
{
Request request = result as Request;
JavaScriptSerializer serializer = new JavaScriptSerializer();
request.HttpContext.Response.ContentType = "text/json";
request.HttpContext.Response.Write(serializer.Serialize(request.Response));
request.HttpContext.Response.End();
}
#endregion
#endregion
}
}
SUPPORTING CLASSES:
using System;
using System.Runtime.InteropServices;
namespace Concept.LongPolling.LongPolling
{
/// <summary>Represents the executable instance of an asynchronous operation.</summary>
[ComVisible(true)]
public interface IAsynchProcessor : IAsyncResult
{
/// <summary>
/// Gets a value that indicates whether the operation completed sucessfully.
/// </summary>
/// <returns>true if the operation completed sucessfully; otherwise, false.</returns>
bool ProcessRequest();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
namespace Concept.LongPolling.LongPolling
{
public sealed class Service
{
#region CONSTRUCTORS
private Service()
{
requests = new List<IAsynchProcessor>();
backgroundThread = new Thread(new ThreadStart(MainLoop));
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
#endregion
#region PROPERTIES
private static Service singleton;
private Thread backgroundThread;
private List<IAsynchProcessor> requests;
static readonly object padlock = new object();
public static Service Singleton
{
get
{
if (_singleton == null)
lock (_padlock)
{
if (_singleton == null)
_singleton = new Service();
}
return _singleton;
}
}
#endregion
#region METHODS
private void MainLoop()
{
while (true)
{
foreach (IAsynchProcessor request in requests.ToArray())
{
if (request.ProcessRequest())
requests.Remove(request);
}
Thread.Sleep(500);
}
}
public void AddRequest(IAsynchProcessor request)
{
lock (padlock)
{
requests.Add(request);
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Concept.LongPolling.Business;
using System.Data;
namespace Concept.LongPolling.Handlers
{
public class Response
{
#region CONSTRUCTORS
public Response()
{
SessionValid = true;
Exception = String.Empty;
}
#endregion
#region PROPERTIES
public const int TimeOffset = 120;
public Int32 Number { get; set; }
public bool SessionValid { get; set; }
public String Exception { get; set; }
#endregion
#region METHODS
public void Generate()
{
// do some desired operation
Number += 1;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Concept.LongPolling.LongPolling;
namespace Concept.LongPolling.Handlers
{
public class Request : IAsynchProcessor
{
#region CONSTRUCTORS
public Request(AsyncCallback callback, HttpContext context)
{
asyncCallback = callback;
httpContext = context;
createdTime = DateTime.Now;
Response = new Response();
}
#endregion
#region PROPERTIES
public const int TimeoutSeconds = 15;
private AsyncCallback asyncCallback;
private HttpContext httpContext;
private DateTime createdTime;
public bool TimedOut
{
get
{
return ((DateTime.Now - createdTime).TotalSeconds >= TimeoutSeconds);
}
}
public Response Response { get; set; }
#region IAsyncResult Members
public HttpContext HttpContext
{
get
{
return httpContext;
}
}
public object AsyncState { get; set; }
System.Threading.WaitHandle IAsyncResult.AsyncWaitHandle
{
get { throw new NotImplementedException(); }
}
bool IAsyncResult.CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return isCompleted; }
set
{
if (!value) return;
this.isCompleted = true;
asyncCallback(this);
}
}
bool isCompleted = false;
#endregion
#endregion
#region METHODS
public bool ProcessRequest()
{
this.Response = Controller.CreateResponse(this.Response);
this.IsCompleted = true;
return this.IsCompleted;
}
#endregion
}
}
Take a look at this article, which describes how to execute a method asynchronously, and uses an event handler that fires when the asynchronous method call has completed.
http://www.csharp-examples.net/create-asynchronous-method/
Here's a rough draft of how you would apply the contents of the article in your situation. I haven't tested the code, so it might not be perfect, but it should be close.
You need to import the following namespaces:
using System.Threading;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;
And here is the rough implementation:
//boolean flag which indicates whether the async task is running
private bool crawling = false;
private delegate bool CrawlWebsiteDelegate();
private bool CrawlWebsite()
{
//crawl the website
return false;
}
protected void Button1_Click(object sender, EventArgs e)
{
CrawlWebsiteDelegate worker = new CrawlWebsiteDelegate(CrawlWebsite);
AsyncCallback completedCallback = new AsyncCallback(CrawlWebsiteCompletedCallback);
if (!crawling)
{
worker.BeginInvoke(completedCallback, AsyncOperationManager.CreateOperation(null));
crawling = true;
}
}
private void CrawlWebsiteCompletedCallback(IAsyncResult ar)
{
//get the original worker delegate and the AsyncOperation instance
CrawlWebsiteDelegate worker = (CrawlWebsiteDelegate)((AsyncResult)ar).AsyncDelegate;
//finish the asynchronous operation
bool success = worker.EndInvoke(ar);
crawling = false;
if (success)
{
//perform sql tasks now that crawl has completed
}
}
EDIT: Here is the code in VB.NET - not positive that all syntax is correct
Private crawling As Boolean = False
Private Delegate Function CrawlWebsiteDelegate() As Boolean
Private Function CrawlWebsite() As Boolean
Return False
End Function
Protected Sub Button1_Click(sender As Object, e As EventArgs)
Dim worker As New CrawlWebsiteDelegate(AddressOf CrawlWebsite)
Dim completedCallback As New AsyncCallback(AddressOf CrawlWebsiteCompletedCallback)
If Not crawling Then
worker.BeginInvoke(completedCallback, AsyncOperationManager.CreateOperation(Nothing))
crawling = True
End If
End Sub
Private Sub CrawlWebsiteCompletedCallback(ar As IAsyncResult)
Dim worker As CrawlWebsiteDelegate = DirectCast(DirectCast(ar, AsyncResult).AsyncDelegate, CrawlWebsiteDelegate)
Dim success As Boolean = worker.EndInvoke(ar)
crawling = False
If success Then
DoSomeSqlTasks()
End If
End Sub
I am using DataAnnotations for my model validation i.e.
[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
In my controller, I am checking the value of ModelState. This is correctly returning false for invalid model data posted from my view.
However, when executing the unit test of my controller action, ModelState always returns true:
[TestMethod]
public void Submitting_Empty_Shipping_Details_Displays_Default_View_With_Error()
{
// Arrange
CartController controller = new CartController(null, null);
Cart cart = new Cart();
cart.AddItem(new Product(), 1);
// Act
var result = controller.CheckOut(cart, new ShippingDetails() { Name = "" });
// Assert
Assert.IsTrue(string.IsNullOrEmpty(result.ViewName));
Assert.IsFalse(result.ViewData.ModelState.IsValid);
}
Do I need to do anything extra to set up the model validation in my tests?
I posted this in my blog post:
using System.ComponentModel.DataAnnotations;
// model class
public class Fiz
{
[Required]
public string Name { get; set; }
[Required]
[RegularExpression(".+#..+")]
public string Email { get; set; }
}
// in test class
[TestMethod]
public void EmailRequired()
{
var fiz = new Fiz
{
Name = "asdf",
Email = null
};
Assert.IsTrue(ValidateModel(fiz).Any(
v => v.MemberNames.Contains("Email") &&
v.ErrorMessage.Contains("required")));
}
private IList<ValidationResult> ValidateModel(object model)
{
var validationResults = new List<ValidationResult>();
var ctx = new ValidationContext(model, null, null);
Validator.TryValidateObject(model, ctx, validationResults, true);
return validationResults;
}
Validation will be performed by the ModelBinder. In the example, you construct the ShippingDetails yourself, which will skip the ModelBinder and thus, validation entirely. Note the difference between input validation and model validation. Input validation is to make sure the user provided some data, given he had the chance to do so. If you provide a form without the associated field, the associated validator won't be invoked.
There have been changes in MVC2 on model validation vs. input validation, so the exact behaviour depends on the version you are using. See http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html for details on this regarding both MVC and MVC 2.
[EDIT] I guess the cleanest solution to this is to call UpdateModel on the Controller manually when testing by providing a custom mock ValueProvider. That should fire validation and set the ModelState correctly.
I was going through http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html, in this post I didn't like the idea of putting the validation tests in controller test and somewhat manual checking in each test that if the validation attribute exists or not. So, below is the helper method and it's usage which I implemented, it works for both EDM (which has metadata attributes, because of the reason we can not apply attributes on auto generated EDM classes) and POCO objects which have ValidationAttributes applied to their properties.
The helper method does not parse into hierarchical objects, but validation can be tested on flat individual objects(Type-level)
class TestsHelper
{
internal static void ValidateObject<T>(T obj)
{
var type = typeof(T);
var meta = type.GetCustomAttributes(false).OfType<MetadataTypeAttribute>().FirstOrDefault();
if (meta != null)
{
type = meta.MetadataClassType;
}
var propertyInfo = type.GetProperties();
foreach (var info in propertyInfo)
{
var attributes = info.GetCustomAttributes(false).OfType<ValidationAttribute>();
foreach (var attribute in attributes)
{
var objPropInfo = obj.GetType().GetProperty(info.Name);
attribute.Validate(objPropInfo.GetValue(obj, null), info.Name);
}
}
}
}
/// <summary>
/// Link EDM class with meta data class
/// </summary>
[MetadataType(typeof(ServiceMetadata))]
public partial class Service
{
}
/// <summary>
/// Meta data class to hold validation attributes for each property
/// </summary>
public class ServiceMetadata
{
/// <summary>
/// Name
/// </summary>
[Required]
[StringLength(1000)]
public object Name { get; set; }
/// <summary>
/// Description
/// </summary>
[Required]
[StringLength(2000)]
public object Description { get; set; }
}
[TestFixture]
public class ServiceModelTests
{
[Test]
[ExpectedException(typeof(ValidationException), ExpectedMessage = "The Name field is required.")]
public void Name_Not_Present()
{
var serv = new Service{Name ="", Description="Test"};
TestsHelper.ValidateObject(serv);
}
[Test]
[ExpectedException(typeof(ValidationException), ExpectedMessage = "The Description field is required.")]
public void Description_Not_Present()
{
var serv = new Service { Name = "Test", Description = string.Empty};
TestsHelper.ValidateObject(serv);
}
}
this is another post http://johan.driessen.se/archive/2009/11/18/testing-dataannotation-based-validation-in-asp.net-mvc.aspx which talks about validating in .Net 4, but i think i am going to stick to my helper method which is valid in both 3.5 and 4
I like to test the data attributes on my models and view models outside the context of the controller. I've done this by writing my own version of TryUpdateModel that doesn't need a controller and can be used to populate a ModelState dictionary.
Here is my TryUpdateModel method (mostly taken from the .NET MVC Controller source code):
private static ModelStateDictionary TryUpdateModel<TModel>(TModel model,
IValueProvider valueProvider) where TModel : class
{
var modelState = new ModelStateDictionary();
var controllerContext = new ControllerContext();
var binder = ModelBinders.Binders.GetBinder(typeof(TModel));
var bindingContext = new ModelBindingContext()
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
() => model, typeof(TModel)),
ModelState = modelState,
ValueProvider = valueProvider
};
binder.BindModel(controllerContext, bindingContext);
return modelState;
}
This can then be easily used in a unit test like this:
// Arrange
var viewModel = new AddressViewModel();
var addressValues = new FormCollection
{
{"CustomerName", "Richard"}
};
// Act
var modelState = TryUpdateModel(viewModel, addressValues);
// Assert
Assert.False(modelState.IsValid);
I had an issue where TestsHelper worked most of the time but not for validation methods defined by the IValidatableObject interface. The CompareAttribute also gave me some problems. That is why the try/catch is in there. The following code seems to validate all cases:
public static void ValidateUsingReflection<T>(T obj, Controller controller)
{
ValidationContext validationContext = new ValidationContext(obj, null, null);
Type type = typeof(T);
MetadataTypeAttribute meta = type.GetCustomAttributes(false).OfType<MetadataTypeAttribute>().FirstOrDefault();
if (meta != null)
{
type = meta.MetadataClassType;
}
PropertyInfo[] propertyInfo = type.GetProperties();
foreach (PropertyInfo info in propertyInfo)
{
IEnumerable<ValidationAttribute> attributes = info.GetCustomAttributes(false).OfType<ValidationAttribute>();
foreach (ValidationAttribute attribute in attributes)
{
PropertyInfo objPropInfo = obj.GetType().GetProperty(info.Name);
try
{
validationContext.DisplayName = info.Name;
attribute.Validate(objPropInfo.GetValue(obj, null), validationContext);
}
catch (Exception ex)
{
controller.ModelState.AddModelError(info.Name, ex.Message);
}
}
}
IValidatableObject valObj = obj as IValidatableObject;
if (null != valObj)
{
IEnumerable<ValidationResult> results = valObj.Validate(validationContext);
foreach (ValidationResult result in results)
{
string key = result.MemberNames.FirstOrDefault() ?? string.Empty;
controller.ModelState.AddModelError(key, result.ErrorMessage);
}
}
}
Given two tables, Make and Model, where a make can contain many models and resulting in the following EF generated entity types...
/// <KeyProperties>
/// ID
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="CarsModel", Name="Make")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Make : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Make object.
/// </summary>
/// <param name="id">Initial value of ID.</param>
public static Make CreateMake(int id)
{
Make make = new Make();
make.ID = id;
return make;
}
/// <summary>
/// There are no comments for Property ID in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int ID
{
get
{
return this._ID;
}
set
{
this.OnIDChanging(value);
this.ReportPropertyChanging("ID");
this._ID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("ID");
this.OnIDChanged();
}
}
private int _ID;
partial void OnIDChanging(int value);
partial void OnIDChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Models in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("CarsModel", "FK_Model_Make", "Model")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityCollection<Model> Models
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<Model>("CarsModel.FK_Model_Make", "Model");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<Model>("CarsModel.FK_Model_Make", "Model", value);
}
}
}
}
/// <KeyProperties>
/// ID
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="CarsModel", Name="Model")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Model : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Model object.
/// </summary>
/// <param name="id">Initial value of ID.</param>
public static Model CreateModel(int id)
{
Model model = new Model();
model.ID = id;
return model;
}
/// <summary>
/// There are no comments for Property ID in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int ID
{
get
{
return this._ID;
}
set
{
this.OnIDChanging(value);
this.ReportPropertyChanging("ID");
this._ID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("ID");
this.OnIDChanged();
}
}
private int _ID;
partial void OnIDChanging(int value);
partial void OnIDChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Make in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("CarsModel", "FK_Model_Make", "Make")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public Make Make
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make").Value;
}
set
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make").Value = value;
}
}
/// <summary>
/// There are no comments for Make in the schema.
/// </summary>
[global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityReference<Make> MakeReference
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Make>("CarsModel.FK_Model_Make", "Make", value);
}
}
}
I am trying to store an instance of the Make class into ASP.NET ViewState, along with the associated models as follows...
private Make Make {
get { return this.ViewState[#"EditContext"] as Make; }
set { this.ViewState[#"EditContext"] = value; }
}
and
this.Make = (from make in context.Makes.Include(#"Models")
where make.ID == 1
select make).FirstOrDefault();
But upon PostBack, this.Make.Models is always empty (depite definitely being populated when the entity was placed into the ViewState.
According to the MS Help,
Because entity types support binary
serialization, objects can be saved in
the view state of an ASP.NET
application during a postback
operation. When required, the object
and its related objects are retrieved
from the view state and attached to an
existing object context.
I would therefore expect what I am doing to work. Can anybody explain why this is not the case?
Thanks.
It seems that the problem was my own fault.
After adding the entity to the ViewState, I was manually detaching it from the object context. This was then clearing the links between the Make and the associated Model objects.
By simply adding the object to the ViewState without calling context.Detach(), the Models remain in the list, and I can still call context.Attach() to facilitate the manipulation of the object during the postback.
I'm using ASP.NET MVC and I'd like all user entered string fields to be trimmed before they're inserted into the database. And since I have many data entry forms, I'm looking for an elegant way to trim all strings instead of explicitly trimming every user supplied string value. I'm interested to know how and when people are trimming strings.
I thought about perhaps creating a custom model binder and trimming any string values there...that way, all my trimming logic is contained in one place. Is this a good approach? Are there any code samples that do this?
public class TrimModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
if (propertyDescriptor.PropertyType == typeof(string))
{
var stringValue = (string)value;
if (!string.IsNullOrWhiteSpace(stringValue))
{
value = stringValue.Trim();
}
else
{
value = null;
}
}
base.SetProperty(controllerContext, bindingContext,
propertyDescriptor, value);
}
}
How about this code?
ModelBinders.Binders.DefaultBinder = new TrimModelBinder();
Set global.asax Application_Start event.
This is #takepara same resolution but as an IModelBinder instead of DefaultModelBinder so that adding the modelbinder in global.asax is through
ModelBinders.Binders.Add(typeof(string),new TrimModelBinder());
The class:
public class TrimModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueResult== null || valueResult.AttemptedValue==null)
return null;
else if (valueResult.AttemptedValue == string.Empty)
return string.Empty;
return valueResult.AttemptedValue.Trim();
}
}
based on #haacked post:
http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx
One improvement to #takepara answer.
Somewere in project:
public class NoTrimAttribute : Attribute { }
In TrimModelBinder class change
if (propertyDescriptor.PropertyType == typeof(string))
to
if (propertyDescriptor.PropertyType == typeof(string) && !propertyDescriptor.Attributes.Cast<object>().Any(a => a.GetType() == typeof(NoTrimAttribute)))
and you can mark properties to be excluded from trimming with [NoTrim] attribute.
In ASP.Net Core 2 this worked for me. I'm using the [FromBody] attribute in my controllers and JSON input. To override the string handling in the JSON deserialization I registered my own JsonConverter:
services.AddMvcCore()
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Insert(0, new TrimmingStringConverter());
})
And this is the converter:
public class TrimmingStringConverter : JsonConverter
{
public override bool CanRead => true;
public override bool CanWrite => false;
public override bool CanConvert(Type objectType) => objectType == typeof(string);
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
if (reader.Value is string value)
{
return value.Trim();
}
return reader.Value;
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
With improvements in C# 6, you can now write a very compact model binder that will trim all string inputs:
public class TrimStringModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var attemptedValue = value?.AttemptedValue;
return string.IsNullOrWhiteSpace(attemptedValue) ? attemptedValue : attemptedValue.Trim();
}
}
You need to include this line somewhere in Application_Start() in your Global.asax.cs file to use the model binder when binding strings:
ModelBinders.Binders.Add(typeof(string), new TrimStringModelBinder());
I find it is better to use a model binder like this, rather than overriding the default model binder, because then it will be used whenever you are binding a string, whether that's directly as a method argument or as a property on a model class. However, if you override the default model binder as other answers here suggest, that will only work when binding properties on models, not when you have a string as an argument to an action method
Edit: a commenter asked about dealing with the situation when a field should not be validated. My original answer was reduced to deal just with the question the OP had posed, but for those who are interested, you can deal with validation by using the following extended model binder:
public class TrimStringModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest && bindingContext.ModelMetadata.RequestValidationEnabled;
var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;
var value = unvalidatedValueProvider == null ?
bindingContext.ValueProvider.GetValue(bindingContext.ModelName) :
unvalidatedValueProvider.GetValue(bindingContext.ModelName, !shouldPerformRequestValidation);
var attemptedValue = value?.AttemptedValue;
return string.IsNullOrWhiteSpace(attemptedValue) ? attemptedValue : attemptedValue.Trim();
}
}
Another variant of #takepara's answer but with a different twist:
1) I prefer the opt-in "StringTrim" attribute mechanism (rather than the opt-out "NoTrim" example of #Anton).
2) An additional call to SetModelValue is required to ensure the ModelState is populated correctly and the default validation/accept/reject pattern can be used as normal, i.e. TryUpdateModel(model) to apply and ModelState.Clear() to accept all changes.
Put this in your entity/shared library:
/// <summary>
/// Denotes a data field that should be trimmed during binding, removing any spaces.
/// </summary>
/// <remarks>
/// <para>
/// Support for trimming is implmented in the model binder, as currently
/// Data Annotations provides no mechanism to coerce the value.
/// </para>
/// <para>
/// This attribute does not imply that empty strings should be converted to null.
/// When that is required you must additionally use the <see cref="System.ComponentModel.DataAnnotations.DisplayFormatAttribute.ConvertEmptyStringToNull"/>
/// option to control what happens to empty strings.
/// </para>
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class StringTrimAttribute : Attribute
{
}
Then this in your MVC application/library:
/// <summary>
/// MVC model binder which trims string values decorated with the <see cref="StringTrimAttribute"/>.
/// </summary>
public class StringTrimModelBinder : IModelBinder
{
/// <summary>
/// Binds the model, applying trimming when required.
/// </summary>
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Get binding value (return null when not present)
var propertyName = bindingContext.ModelName;
var originalValueResult = bindingContext.ValueProvider.GetValue(propertyName);
if (originalValueResult == null)
return null;
var boundValue = originalValueResult.AttemptedValue;
// Trim when required
if (!String.IsNullOrEmpty(boundValue))
{
// Check for trim attribute
if (bindingContext.ModelMetadata.ContainerType != null)
{
var property = bindingContext.ModelMetadata.ContainerType.GetProperties()
.FirstOrDefault(propertyInfo => propertyInfo.Name == bindingContext.ModelMetadata.PropertyName);
if (property != null && property.GetCustomAttributes(true)
.OfType<StringTrimAttribute>().Any())
{
// Trim when attribute set
boundValue = boundValue.Trim();
}
}
}
// Register updated "attempted" value with the model state
bindingContext.ModelState.SetModelValue(propertyName, new ValueProviderResult(
originalValueResult.RawValue, boundValue, originalValueResult.Culture));
// Return bound value
return boundValue;
}
}
If you don't set the property value in the binder, even when you don't want to change anything, you will block that property from ModelState altogether! This is because you are registered as binding all string types, so it appears (in my testing) that the default binder will not do it for you then.
Extra info for anyone searching how to do this in ASP.NET Core 1.0. Logic has changed quite a lot.
I wrote a blog post about how to do it, it explains things in bit more detailed
So ASP.NET Core 1.0 solution:
Model binder to do the actual trimming
public class TrimmingModelBinder : ComplexTypeModelBinder
{
public TrimmingModelBinder(IDictionary propertyBinders) : base(propertyBinders)
{
}
protected override void SetProperty(ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result)
{
if(result.Model is string)
{
string resultStr = (result.Model as string).Trim();
result = ModelBindingResult.Success(resultStr);
}
base.SetProperty(bindingContext, modelName, propertyMetadata, result);
}
}
Also you need Model Binder Provider in the latest version, this tells that should this binder be used for this model
public class TrimmingModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
{
var propertyBinders = new Dictionary();
foreach (var property in context.Metadata.Properties)
{
propertyBinders.Add(property, context.CreateBinder(property));
}
return new TrimmingModelBinder(propertyBinders);
}
return null;
}
}
Then it has to be registered in Startup.cs
services.AddMvc().AddMvcOptions(options => {
options.ModelBinderProviders.Insert(0, new TrimmingModelBinderProvider());
});
In case of MVC Core
Binder:
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
public class TrimmingModelBinder
: IModelBinder
{
private readonly IModelBinder FallbackBinder;
public TrimmingModelBinder(IModelBinder fallbackBinder)
{
FallbackBinder = fallbackBinder ?? throw new ArgumentNullException(nameof(fallbackBinder));
}
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult != null &&
valueProviderResult.FirstValue is string str &&
!string.IsNullOrEmpty(str))
{
bindingContext.Result = ModelBindingResult.Success(str.Trim());
return Task.CompletedTask;
}
return FallbackBinder.BindModelAsync(bindingContext);
}
}
Provider:
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using System;
public class TrimmingModelBinderProvider
: IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (!context.Metadata.IsComplexType && context.Metadata.ModelType == typeof(string))
{
return new TrimmingModelBinder(new SimpleTypeModelBinder(context.Metadata.ModelType));
}
return null;
}
}
Registration function:
public static void AddStringTrimmingProvider(this MvcOptions option)
{
var binderToFind = option.ModelBinderProviders
.FirstOrDefault(x => x.GetType() == typeof(SimpleTypeModelBinderProvider));
if (binderToFind == null)
{
return;
}
var index = option.ModelBinderProviders.IndexOf(binderToFind);
option.ModelBinderProviders.Insert(index, new TrimmingModelBinderProvider());
}
Register:
service.AddMvc(option => option.AddStringTrimmingProvider())
I created value providers to trim the query string parameter values and the form values. This was tested with ASP.NET Core 3 and works perfectly.
public class TrimmedFormValueProvider
: FormValueProvider
{
public TrimmedFormValueProvider(IFormCollection values)
: base(BindingSource.Form, values, CultureInfo.InvariantCulture)
{ }
public override ValueProviderResult GetValue(string key)
{
ValueProviderResult baseResult = base.GetValue(key);
string[] trimmedValues = baseResult.Values.Select(v => v?.Trim()).ToArray();
return new ValueProviderResult(new StringValues(trimmedValues));
}
}
public class TrimmedQueryStringValueProvider
: QueryStringValueProvider
{
public TrimmedQueryStringValueProvider(IQueryCollection values)
: base(BindingSource.Query, values, CultureInfo.InvariantCulture)
{ }
public override ValueProviderResult GetValue(string key)
{
ValueProviderResult baseResult = base.GetValue(key);
string[] trimmedValues = baseResult.Values.Select(v => v?.Trim()).ToArray();
return new ValueProviderResult(new StringValues(trimmedValues));
}
}
public class TrimmedFormValueProviderFactory
: IValueProviderFactory
{
public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
{
if (context.ActionContext.HttpContext.Request.HasFormContentType)
context.ValueProviders.Add(new TrimmedFormValueProvider(context.ActionContext.HttpContext.Request.Form));
return Task.CompletedTask;
}
}
public class TrimmedQueryStringValueProviderFactory
: IValueProviderFactory
{
public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
{
context.ValueProviders.Add(new TrimmedQueryStringValueProvider(context.ActionContext.HttpContext.Request.Query));
return Task.CompletedTask;
}
}
Then register the value provider factories in the ConfigureServices() function in Startup.cs
services.AddControllersWithViews(options =>
{
int formValueProviderFactoryIndex = options.ValueProviderFactories.IndexOf(options.ValueProviderFactories.OfType<FormValueProviderFactory>().Single());
options.ValueProviderFactories[formValueProviderFactoryIndex] = new TrimmedFormValueProviderFactory();
int queryStringValueProviderFactoryIndex = options.ValueProviderFactories.IndexOf(options.ValueProviderFactories.OfType<QueryStringValueProviderFactory>().Single());
options.ValueProviderFactories[queryStringValueProviderFactoryIndex] = new TrimmedQueryStringValueProviderFactory();
});
While reading through the excellent answers and comments above, and becoming increasingly confused, I suddenly thought, hey, I wonder if there's a jQuery solution. So for others who, like me, find ModelBinders a bit bewildering, I offer the following jQuery snippet that trims the input fields before the form gets submitted.
$('form').submit(function () {
$(this).find('input:text').each(function () {
$(this).val($.trim($(this).val()));
})
});
Late to the party, but the following is a summary of adjustments required for MVC 5.2.3 if you are to handle the skipValidation requirement of the build-in value providers.
public class TrimStringModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// First check if request validation is required
var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest &&
bindingContext.ModelMetadata.RequestValidationEnabled;
// determine if the value provider is IUnvalidatedValueProvider, if it is, pass in the
// flag to perform request validation (e.g. [AllowHtml] is set on the property)
var unvalidatedProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;
var valueProviderResult = unvalidatedProvider?.GetValue(bindingContext.ModelName, !shouldPerformRequestValidation) ??
bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return valueProviderResult?.AttemptedValue?.Trim();
}
}
Global.asax
protected void Application_Start()
{
...
ModelBinders.Binders.Add(typeof(string), new TrimStringModelBinder());
...
}
Update: This answer is out of date for recent versions of ASP.NET Core. Use Bassem's answer instead.
For ASP.NET Core, replace the ComplexTypeModelBinderProvider with a provider that trims strings.
In your startup code ConfigureServices method, add this:
services.AddMvc()
.AddMvcOptions(s => {
s.ModelBinderProviders[s.ModelBinderProviders.TakeWhile(p => !(p is ComplexTypeModelBinderProvider)).Count()] = new TrimmingModelBinderProvider();
})
Define TrimmingModelBinderProvider like this:
/// <summary>
/// Used in place of <see cref="ComplexTypeModelBinderProvider"/> to trim beginning and ending whitespace from user input.
/// </summary>
class TrimmingModelBinderProvider : IModelBinderProvider
{
class TrimmingModelBinder : ComplexTypeModelBinder
{
public TrimmingModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders) : base(propertyBinders) { }
protected override void SetProperty(ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result)
{
var value = result.Model as string;
if (value != null)
result = ModelBindingResult.Success(value.Trim());
base.SetProperty(bindingContext, modelName, propertyMetadata, result);
}
}
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType) {
var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
for (var i = 0; i < context.Metadata.Properties.Count; i++) {
var property = context.Metadata.Properties[i];
propertyBinders.Add(property, context.CreateBinder(property));
}
return new TrimmingModelBinder(propertyBinders);
}
return null;
}
}
The ugly part of this is the copy and paste of the GetBinder logic from ComplexTypeModelBinderProvider, but there doesn't seem to be any hook to let you avoid this.
I disagree with the solution.
You should override GetPropertyValue because the data for SetProperty could also be filled by the ModelState.
To catch the raw data from the input elements write this:
public class CustomModelBinder : System.Web.Mvc.DefaultModelBinder
{
protected override object GetPropertyValue(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, System.Web.Mvc.IModelBinder propertyBinder)
{
object value = base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
string retval = value as string;
return string.IsNullOrWhiteSpace(retval)
? value
: retval.Trim();
}
}
Filter by propertyDescriptor PropertyType if you are really only interested in string values but it should not matter because everything what comes in is basically a string.
There have been a lot of posts suggesting an attribute approach. Here is a package that already has a trim attribute and many others: Dado.ComponentModel.Mutations or NuGet
public partial class ApplicationUser
{
[Trim, ToLower]
public virtual string UserName { get; set; }
}
// Then to preform mutation
var user = new ApplicationUser() {
UserName = " M#X_speed.01! "
}
new MutationContext<ApplicationUser>(user).Mutate();
After the call to Mutate(), user.UserName will be mutated to m#x_speed.01!.
This example will trim whitespace and case the string to lowercase. It doesn't introduce validation, but the System.ComponentModel.Annotations can be used alongside Dado.ComponentModel.Mutations.
I posted this in another thread. In asp.net core 2, I went in a different direction. I used an action filter instead. In this case the developer can either set it globally or use as an attribute for the actions he/she wants to apply the string trimming. This code runs after the model binding has taken place, and it can update the values in the model object.
Here is my code, first create an action filter:
public class TrimInputStringsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
foreach (var arg in context.ActionArguments)
{
if (arg.Value is string)
{
string val = arg.Value as string;
if (!string.IsNullOrEmpty(val))
{
context.ActionArguments[arg.Key] = val.Trim();
}
continue;
}
Type argType = arg.Value.GetType();
if (!argType.IsClass)
{
continue;
}
TrimAllStringsInObject(arg.Value, argType);
}
}
private void TrimAllStringsInObject(object arg, Type argType)
{
var stringProperties = argType.GetProperties()
.Where(p => p.PropertyType == typeof(string));
foreach (var stringProperty in stringProperties)
{
string currentValue = stringProperty.GetValue(arg, null) as string;
if (!string.IsNullOrEmpty(currentValue))
{
stringProperty.SetValue(arg, currentValue.Trim(), null);
}
}
}
}
To use it, either register as global filter or decorate your actions with the TrimInputStrings attribute.
[TrimInputStrings]
public IActionResult Register(RegisterViewModel registerModel)
{
// Some business logic...
return Ok();
}
OK, I have this thing and it kinda works:
class TrimmingModelBinder : IModelBinder
{
public Task BindModelAsync (ModelBindingContext ctx)
{
if
(
ctx .ModelName is string name
&& ctx .ValueProvider .GetValue (name) .FirstValue is string v)
ctx .ModelState .SetModelValue
(
name,
new ValueProviderResult
((ctx .Result = ModelBindingResult .Success (v .Trim ())) .Model as string));
return Task .CompletedTask; }}
class AutoTrimAttribute : ModelBinderAttribute
{
public AutoTrimAttribute ()
{ this .BinderType = typeof (TrimmingModelBinder); }}
It is a shame that there is no standard feature for this though.
I adapted #Kai G's answer for System.Text.Json:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class TrimmedStringConverter : JsonConverter<string>
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(string);
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetString() is string value ? value.Trim() : null;
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}