Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7167559
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T14:36:03+00:00 2026-05-28T14:36:03+00:00

I have a set of services hosted with WCF Web Api, what I need

  • 0

I have a set of services hosted with WCF Web Api, what I need to do is validate the properties inside the models of the app.

In MVC 3 for example I decorate properties in the model like this:

    [StringLength(30)]
    public string UserName { get; set; }

and then in the controller I proceed like this to verify os the model has met the validation parameters:

    [HttpPost]
    ActionResult Create(Model myModel)
    { 
        if(ModelState.IsValid(){
           Post the model
        }
        else
        {
           Don't post the model
        }
    }

Is there a way to do something similar in WCF Web Api?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T14:36:04+00:00Added an answer on May 28, 2026 at 2:36 pm

    Firstly I should say awesome question+answer Daniel

    However, I’ve taken it a little further, refined it and added to it.

    ValidationHander

    I’ve refined this a little. It is now based on a generic HttpOperationHandler so it can take the HttpRequestMessage. The reason for this is so that I can return error messages formatted using the correct media type (from the accept header).

    public class ValidationHandler<TResource> : HttpOperationHandler<TResource, HttpRequestMessage, HttpRequestMessage>
    {
        public ValidationHandler() : base("response") { }
    
        protected override HttpRequestMessage OnHandle(TResource model, HttpRequestMessage requestMessage)
        {
            var results = new List<ValidationResult>();
            var context = new ValidationContext(model, null, null);
            Validator.TryValidateObject(model, context, results, true);
    
            if (results.Count == 0)
            {
                return requestMessage;
            }
    
            var errorMessages = results.Select(x => x.ErrorMessage).ToArray();
    
            var mediaType = requestMessage.Headers.Accept.FirstOrDefault();
            var response = new RestValidationFailure(errorMessages);
            if (mediaType != null)
            {
                response.Content = new ObjectContent(typeof (string[]), errorMessages, mediaType);
            }
            throw new HttpResponseException(response);
        }
    }
    

    Extension Methods

    The 2 you provided stay virtually the same about from the desc paramter no longer being needed when adding the ValidationHandler in the ModelValidationFor method

    I’ve added an extra extension method. This is to make sure that all “Resource” classes are validated. This is mainly me being lazy and forgetful. I am forever forgetting to add some class to a list somewhere. (It’s why I write generic windsor installers!)

    public static void ValidateAllResourceTypes(this WebApiConfiguration config, string assemblyFilter = "MyCompany*.dll")
    {
        var path = Path.GetDirectoryName((new Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath);
        var dc = new DirectoryCatalog(path, assemblyFilter);
        var assemblies = dc.LoadedFiles.Select(Assembly.LoadFrom).ToList();
        assemblies.ForEach(assembly =>
        {
            var resourceTypes = assembly.GetTypes()
                .Where(t => t.Namespace != null && t.Namespace.EndsWith("Resources"));
    
            foreach (var resourceType in resourceTypes)
            {
                var configType = typeof(Extensions);
                var mi = configType.GetMethod("ModelValidationFor");
                var mi2 = mi.MakeGenericMethod(resourceType);
                mi2.Invoke(null, new object[] { config });
            }
        });            
    }
    

    I made use of the System.ComponentModel.Composition.Hosting namespace (formerly known as MEF) for the DirectoryCatalog class. In this case I’ve just used the namespace ending with “Resources” to find my “Resource” classes. It wouldn’t take much work to change it to use a custom attribute or whatever other way you might prefer to identify which classes are your “Resources”.

    RestValidationFailure

    This is a little helper class I made to allow consistent behaviour for validation failure responses.

    public class RestValidationFailure : HttpResponseMessage
    {
        public RestValidationFailure(string[] messages)
        {
            StatusCode = HttpStatusCode.BadRequest;
            foreach (var errorMessage in messages)
            {
                Headers.Add("X-Validation-Error", errorMessage);
            }
        }
    }
    

    So, now I get a nice list (in my preferred mediatype) of all the validation errors.

    Enjoy! 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a set of existing WCF services hosted in a .NET 3.0 app.
I have a set of WCF web services connected to dynamically by a desktop
We have a set of (ASMX but could be WCF) 64-bit web services which
We have a set of WCF Services being hosted in IIS. In our architecture,
I have a self-hosted WCF service with the InstanceContextMode set to PerSession. How can
I have Reporting Services set up with Forms Authentication. Our app is sitting over
I have an WSDL / Web Service and I need to generate an set
Have a bunch of WCF REST services hosted on Azure that access a SQL
I have a simple WCF service hosted in a console app and what I
I have an existing set of singleton WCF services. They are long-running processes that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.