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 8340411
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T05:10:29+00:00 2026-06-09T05:10:29+00:00

I am trying to find a solution to validate if XML data sent in

  • 0

I am trying to find a solution to validate if XML data sent in a POST request are fulfilling a given custom XML schema.

If I use the XmlMediaTypeFormatter delivered with ASP.NET Web API I don’t have a schema validation available, as far as I can see. For example: If I have a model type…

public class Order
{
    public string Code { get; set; }
    public int Quantity { get; set; }
}

…and a POST action in an ApiController…

public HttpResponseMessage Post(Order order)
{
    if (ModelState.IsValid)
    {
        // process order...
        // send 200 OK response for example
    }
    else
        // send 400 BadRequest response with ModelState errors in response body
}

…I can post the following “wrong” XML data and will get a 200 OK response nevertheless:

User-Agent: Fiddler
Host: localhost:45678
Content-Type: application/xml; charset=utf-8

<Order> <Code>12345</Nonsense> </Order>   // malformed XML

Or:

<Order> <CustomerName>12345</CustomerName> </Order>    // invalid property

Or:

<Customer> <Code>12345</Code> </Customer>    // invalid root

Or:

"Hello World"    // no XML at all

etc., etc.

The only point where I have a validation of the request is model binding: In request example 1, 3 and 4 the order passed into the Post method is null, in example 2 the order.Code property is null which I could invalidate by testing for order == null or by marking the Code property with a [Required] attribute. I could send this validation result back in the response with a 400 “BadRequest” Http status code and validation messages in the response body. But I cannot tell exactly what was wrong and can’t distinguish between the wrong XML in example 1, 3 and 4 (no order has been posted, that’s the only thing I can see) – for instance.

Requiring that an Order has to be posted with a specific custom XML schema, for example xmlns="http://test.org/OrderSchema.xsd", I would like to validate if the posted XML is valid with respect to this schema and, if not, send schema validation errors back in the response. To achieve this I have started with a custom MediaTypeFormatter:

public class MyXmlMediaTypeFormatter : MediaTypeFormatter
{
    // constructor, CanReadType, CanWriteType, ...

    public override Task<object> ReadFromStreamAsync(Type type, Stream stream,
        HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
    {
        var task = Task.Factory.StartNew(() =>
        {
            using (var streamReader = new StreamReader(stream))
            {
                XDocument document = XDocument.Load(streamReader);
                // TODO: exceptions must the catched here,
                // for example due to malformed XML
                XmlSchemaSet schemaSet = new XmlSchemaSet();
                schemaSet.Add(null, "OrderSchema.xsd");

                var msgs = new List<string>();
                document.Validate(schemaSet, (s, e) => msgs.Add(e.Message));
                // msgs contains now the list of XML schema validation errors
                // I want to send back in the response
                if (msgs.Count == 0)
                {
                    var order = ... // deserialize XML to order
                    return (object)order;
                }
                else
                    // WHAT NOW ?
            }
        });
        return task;
    }
}

This works so far as long as everything is correct.

But I don’t know what to do if msgs.Count > 0. How can I “transfer” this validation result list to the Post action or how can I create a Http response that contains those XML schema validation messages?

Also I am unsure if a custom MediaTypeFormatter is the best extensibility point for such a XML schema validation and if my approach isn’t the wrong way. Would possibly a custom HttpMessageHandler/DelegatingHandler be a better place for this? Or is there perhaps something much simpler out of the box?

  • 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-06-09T05:10:30+00:00Added an answer on June 9, 2026 at 5:10 am

    By trial and error I found a solution (for the WHAT NOW ? placeholder in the question’s code):

    //...
    else
    {
        PostOrderErrors errors = new PostOrderErrors
        {
            XmlValidationErrors = msgs
        };
        HttpResponseMessage response = new HttpResponseMessage(
            HttpStatusCode.BadRequest);
        response.Content = new ObjectContent(typeof(PostOrderErrors), errors,
            GlobalConfiguration.Configuration.Formatters.XmlFormatter);
        throw new HttpResponseException(response);
    }
    

    …with the response class like this:

    public class PostOrderErrors
    {
        public List<string> XmlValidationErrors { get; set; }
        //...
    }
    

    That seems to work and the response looks like this then:

    HTTP/1.1 400 Bad Request
    Content-Type: application/xml; charset=utf-8
    
    <PostOrderErrors xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <XmlValidationErrors>
            <string>Some error text...</string>
            <string>Another error text...</string>
        </XmlValidationErrors>
    </PostOrderErrors>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to find a way to validate a large XML file against an
Hi i am trying to find solution for using resource file with dynamic data
I am trying to find a solution to using array_map('mysql_real_escape_string', $data); on multidimensional arrays,
I am trying to find a solution to prevent race conditions in my application
I was trying to find a solution but did not succeed even if it
I'm trying to find a solution to add HTTP digest auth to a site
I am trying to find a solution that will resolve a recurring deadlock situation
I'm trying to find a solution for pinpointing indoors, specifically inside big crowded places,
I have been trying to find a solution to this one but could not
I'm having troubles trying to find a solution, if any, to this: public class

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.