Felipe Gavilán
Software engineering, asp.net core 3.1: accept and content-type | adding xml support to a web api.
By default, when we create a Web API in ASP.NET Core, it is configured to use JSON. The idea is that different clients of different technologies can communicate with our application, sending and receiving information, using the JSON format. However, some API clients may prefer to use another format, such as XML.
We will configure a Web API to support XML. In addition, we will talk about how our clients can request information in both JSON and XML. We’ll see the Accept and Content-Type headers, and we’ll talk about content negotiation.

Prepating the Project
The first thing we will do is create a Web API in ASP.NET Core 3.1. By default we get a controller called WeatherForecastController . In it we can add a Post method which is going to be a method that will receive an instance of WeatherForecast . In the end, the class should look like this:
In order to receive and send data from our Web API in XML format, we need to configure the corresponding services in the Startup class. Luckily for us, this is as simple as invoking a method in the Startup class. The method is called AddXmlDataContractSerializerFormatters and we can use it as follows:
Receiving Data in XML – Accept
Now that we have our Web API created and configured, we are ready to receive data from it in JSON format. If we run the Web API and invoke it using Postman, it is likely that you will get the data in JSON format. This is because JSON is the default format used. How can we indicate that we want the data in another format? With the Accept header.
According to MDN :
The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand.
Here the idea is that through this header we can indicate to the Web API the data type that we want to be returned to us, whether it’s JSON (application/json), XML (application/xml), among others. The application/json and application/xml values are examples of media types, or MIME types.
In Postman we can ndicate the media type we want to be returned to us, using the Headers tab:

With this, the Web API will return the response in JSON format:
However, if you change the Accept value to “application/xml”, then we will get an answer in XML format:
An indispensable part of the previous XML structure is “xmlns=” http://schemas.datacontract.org/2004/07/WebAPIJSONXML” ; , which is the way to indicate the structure of the XML.
Content Negotiation
We saw two examples, one where we requested a resource with JSON representation and another in XML. However, what if we want to tell the Web API a list of formats which we can accept? We can do this by indicating various media types.
For example:
Accept: application/zip, application/xml
In the previous case, we are requesting two types of media: application/zip and application/xml. We know that our application does not serve application/zip, therefore, our application uses the next value. The Web API will use the first type of content that it finds it can serve. We call this content negotiation.
Content-Type
In addition to our Web API being able to send data in XML format, we want it to receive information in this format. For that we must use the Content-Type header to indicate the media type of the resource to be sent during a POST method:

Then, in the Body tab we place an XML structure (taken from the response obtained from the Web API):

Note that I am including the xmlns attribute to indicate the XML namespace. Without this attribute, you will get an error.
If we press Send, we will get an Ok from the Web API, indicating that we could effectively send the XML.
We can also send a JSON to our Web API if we wish.
- We can easily configure our Web API to provide and receive data in XML format
- The Accept header is used to indicate the media type we accept as a response (this can be JSON, XML, among others)
- Content negotiation refers to the process of determining the best content format for a given request
- The Content-Type header is used to indicate the media type of the resource.
Share this:
Leave a reply cancel reply.
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
Connecting to %s
Notify me of new comments via email.
Notify me of new posts via email.

- Already have a WordPress.com account? Log in now.
- Follow Following
- Copy shortlink
- Report this content
- View post in Reader
- Manage subscriptions
- Collapse this bar
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
What are all the possible values for HTTP "Content-Type" header?
I have to validate the Content-Type header value before passing it to an HTTP request.
Is there a specific list for all the possible values of Content-Type ?
Otherwise, is there a way to validate the content type before using it in an HTTP request?
- http-headers
- httprequest
- content-type
- 19 Valid media types are supposed to be registered with the IANA - you can see a current list here: iana.org/assignments/media-types/media-types.xhtml but note this list can update over time. There is not a fixed allowed list. – Joe May 17, 2014 at 17:56
- 1 Related post - ASP MVC - Are there any constants for the default content types? – RBT Aug 7, 2018 at 12:21
- @Joe: "Valid media types are supposed to be registered with the IANA" - wait, does this mean custom media types (only for use in an application-specific web API that is only going to be called by a custom client application) are not permitted at all? – O. R. Mapper Nov 5, 2018 at 6:52
- 2 @O.R.Mapper i'd read it more as "there is an official list, but i would not be surprised to see lots of others in the wild". In terms of the OP's question, if you were going to try and validate "all types" you'd at least want to validate all registered types. What to do with additional ones is more open-ended. As far as I know there is no requirement to register custom types. – Joe Nov 5, 2018 at 16:07
- Please accept the answer which helped you most in solving your problem. It helps future readers. If the answers weren't helpful leave comments below them. So the poster can update them accordingly. Read What should I do when someone answers my question? to know more. – Roshana Pitigala Sep 4, 2019 at 13:39
4 Answers 4
You can find every content types here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common types are:
Type application:
Type audio:
Type image:
Type multipart:
Type video:
As is defined in RFC 1341 :
In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows: Content-Type := type "/" subtype *[";" parameter] type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token x-token := < The two characters "X-" followed, with no intervening white space, by any token > subtype := token parameter := attribute "=" value attribute := token value := token / quoted-string token := 1*<any CHAR except SPACE, CTLs, or tspecials> tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values
And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source ).
As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).
Also note the comment above:
If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.
You'll notice that a lot of HTTP requests/responses include an X- header of some sort which are self defined, keep this in mind when validating the types.
- RFC 1341 is not relevant to HTTP. – Julian Reschke May 18, 2014 at 12:32
- 2 RFC 1341 describes Content-Type headers which are used in HTTP. How exactly would you say they are unrelated? – Jeroen Vannevel May 18, 2014 at 12:35
- 2 It has been obsoleted and replaced by newer documents multiple times. What's relevant is what < greenbytes.de/tech/webdav/… > (plus the referenced documents) have to say. – Julian Reschke May 18, 2014 at 14:08
I would aim at covering a subset of possible "Content-type" values, you question seems to focus on identifying known content types.
@Jeroen RFC 1341 reference is great, but for an fairly exhaustive list IANA keeps a web page of officially registered media types here .

- Those are not "known" mediatypes (i.e. samples of what has been observed "in the wild") but mediatypes that went through the IANA registration procedures. They are therefore officially registered. Found it important to point this out :) – DaSourcerer May 17, 2016 at 16:24
If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged http http-headers httprequest content-type or ask your own question .
- The Overflow Blog
- After the buzz fades: What our data tells us about emerging technology sentiment
- How to position yourself to land the job you want
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Meaning of 'all president'
- If I don't want to teach, is there any advantage to getting my CFI/CFII?
- Cycles contained in ample enough hypersurfaces
- Did over 1000 people in the US die of cannabis overdose in 2021?
- What battery chemistry is suitable for a "time capsule" applicaton?
- Removing extra vertical space when using cases in a table environment
- Are the articles of the website “言葉の違いが分かる読み物” written by one person or multiple people?
- Possible influence of Phoenician on local dialects in the British Isles during the Iron Age
- "Sort" by element duplication
- Can you be issued a trespass warning on public property for no reason at all?
- Is it possible to create an analytical ephemeris from raw position and velocity of a Body?
- Would lightning bolts be effective against modern military vehicles?
- How can I repair this wire clothes drying rack?
- If US Treasuries at yielding 4-5% right now, why can't I find an ETF that yields that amount?
- Are underage people allowed to defend themselves in court?
- LM317 voltage regulator varying output depending on the load
- Problem with multicolumn table
- Is it ok to say "When we would go to a restaurant ......." instead of "When we went to a restaurant, ....."?
- How to deal with an overpowered player whose level 1 stats are 18's and 19's, with a 25 in strength
- Why is reinforcement learning not widely adopted as an AI tool for agents in well-known games?
- Android Issues were found when checking AAR metadata: androidx.core:core:1.12.0-alpha01 and androidx.core:core-ktx:1.12.0-alpha01
- How to politely decline a take-home test task?
- How precisely does my place of birth need to match my birth certificate when applying for a US Passport?
- Does "Blood Meridian" accurately describe gunpowder manufacture?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Select Product
Machine Translated
Current Release
FAQs and Deployment Guide
Introduction to Citrix Web App Firewall
Configuring the Web App Firewall
Enabling the Web App Firewall
The Web App Firewall Wizard
Manual Configuration
Manual Configuration By Using the Configuration Utility
Manual Configuration By Using the Command Line Interface
Manually Configuring the Signatures Feature
Adding or Removing a Signatures Object
Configuring or Modifying a Signatures Object
Protecting JSON Applications using Signatures
Updating a Signatures Object
Signature Auto Update
Snort rule integration
Exporting a Signatures Object to a File
Edit signatures to add or modify rules
Add signature rule patterns
To Import and Merge Rules
Signature Updates in High-Availability Deployment and Build Upgrades
Overview of Security checks
Top-Level Protections
HTML Cross-Site Scripting Check
HTML SQL Injection Checks
SQL grammar-based protection for HTML and JSON payload
Command injection grammar-based protection for HTML payload
Relaxation and deny rules for handling HTML SQL injection attacks
HTML Command Injection Protection
Custom keyword support for HTML payload
XML External Entity Protection
Buffer Overflow Check
Web App Firewall Support for Google Web Toolkit
Cookie Protection
Cookie Consistency Check
Cookie Hijacking Protection
SameSite cookie attribute
Data Leak Prevention Checks
Credit Card Check
Safe Object Check
Advanced Form Protection Checks
Field Formats Check
Form Field Consistency Check
CSRF Form Tagging Check
Managing CSRF Form Tagging Check Relaxations
URL Protection Checks
Start URL Check
Deny URL Check
XML Protection Checks
XML Format Check
XML Denial-of-Service Check
XML Cross-Site Scripting Check
XML SQL Injection Check
XML Attachment Check
Web Services Interoperability Check
XML Message Validation Check
XML SOAP Fault Filtering Check
JSON Protection Checks
JSON DOS Protection
JSON SQL Protection
JSON cross-site scripting Protection
JSON Command Injection Protection
Custom keyword support for JSON payload
Managing Content Types
Creating Web App Firewall Profiles
Enforce HTTP RFC compliance
Configuring Web App Firewall Profiles
Changing an Web App Firewall Profile Type
Web App Firewall Profile Settings
Detailed troubleshooting with WAF logs
Manage the global bypass and deny lists
File Upload Protection
Exporting and Importing an Web App Firewall Profile
Configuring and Using the Learning Feature
Dynamic Profiling
Supplemental Information about Profiles
Custom error status and message for HTML, XML, or JSON error object
Policy Labels
Firewall Policies
Creating and Configuring Web App Firewall Policies
Binding Web App Firewall Policies
Viewing a Firewall Policy's Bindings
Supplemental Information about Web App Firewall Policies
Auditing Policies
Importing and Exporting Files
Global Configuration
Engine Settings
Confidential Fields
Field Types
XML Content Types
JSON Content Types
Statistics and Reports
Web App Firewall Logs
PCRE Character Encoding Format
Whitehat WASC Signature Types for WAF Use
Streaming Support for Request Processing
Trace HTML Requests with Security Logs
Web App Firewall Support for Cluster Configurations
Debugging and Troubleshooting
Large File Upload Failure
Miscellaneous
Signatures Alert Articles
Signature update version 103
Signature update version 102
Signature update version 101
Signature update version 100
Signature update version 99
Signature update version 98
Signature update version 97
Signature update version 96
Signature update version 95
Signature update version 94
Signature update version 93
Signature update version 92
Signature update version 91
Signature update version 90
Signature update version 89
Signature update version 88
Signature update version 87
Signature update version 86
Signature update version 85
Signature update version 84
Signature update version 83
Signature update version 82
Signature update version 81
Signature update version 80
Signature update version 79
Signature update version 78
Signature update version 77
Signature update version 76
Signature update version 75
Signature update version 74
Signature update version 73
Signature update version 72
Signature update version 71
Signature update version 70
Signature update version 69
Signature update version 68
Signature update version 67
Signature update version 66
Signature update version 65
Signature update version 64
Signature update version 63
Signature update version 62
Signature update version 61
Signature update version 60
Signature update version 59
Signature update version 58
Signature update version 57
Signature update version 56
Signature update version 55
Signature update version 54
Signature update version 53
Signature update version 52
Signature update version 51
Signature update version 50
Signature update version 49
Signature update version 48
Signature update version 47
Signature update version 46
Signature update version 45
Signature update version 44
Signature update version 43
Signature update version 42
Signature update version 41
Signature update version 40
Signature update version 39
Signature update version 38
Signature update version 37
Signature update version 36
Signature update version 35
Signature update version 34
Signature update version 33
Signature update version 32
Signature update version 30
Signature update version 29
Signature update version 28
Signature update version 27
This content has been machine translated dynamically.
Dieser Inhalt ist eine maschinelle Übersetzung, die dynamisch erstellt wurde. (Haftungsausschluss)
Cet article a été traduit automatiquement de manière dynamique. (Clause de non responsabilité)
Este artículo lo ha traducido una máquina de forma dinámica. (Aviso legal)
此内容已经过机器动态翻译。 放弃
このコンテンツは動的に機械翻訳されています。 免責事項
이 콘텐츠는 동적으로 기계 번역되었습니다. 책임 부인
Este texto foi traduzido automaticamente. (Aviso legal)
Questo contenuto è stato tradotto dinamicamente con traduzione automatica. (Esclusione di responsabilità))
This article has been machine translated.
Dieser Artikel wurde maschinell übersetzt. (Haftungsausschluss)
Ce article a été traduit automatiquement. (Clause de non responsabilité)
Este artículo ha sido traducido automáticamente. (Aviso legal)
この記事は機械翻訳されています. 免責事項
이 기사는 기계 번역되었습니다. 책임 부인
Este artigo foi traduzido automaticamente. (Aviso legal)
这篇文章已经过机器翻译. 放弃
Questo articolo è stato tradotto automaticamente. (Esclusione di responsabilità))
Translation failed!
XML content types
By default, the Web App Firewall treats files that follow certain naming conventions as XML. You can configure the Web App Firewall to examine web content for additional strings or patterns that indicate that those files are XML files. This can ensure that the Web App Firewall recognizes all XML content on your site, even if certain XML content does not follow normal XML naming conventions, ensuring that XML content is subjected to XML security checks.
To configure the XML content types, you add the appropriate patterns to the XML Content Types list. You can enter a content type as a string, or you can enter a PCRE-compatible regular expression specifying one or more strings. You can also modify the existing XML content types patterns.
- To add an XML content type pattern by using the command line interface
At the command prompt, type the following commands:
- add appfw XMLContentType <XMLContenttypevalue> [-isRegex ( REGEX | NOTREGEX )]
- save ns config
The following example adds the pattern .*/xml to the XML Content Types list and designates it as a regular expression.
- To remove an XML content type pattern by using the command line interface
- rm appfw XMLContentType <XMLContenttypevalue>
- To configure the XML content type list by using the GUI
- Navigate to Security > Web App Firewall .
- In the details pane, under Settings , click Manage XML Content Types .
- To add a new XML content type, click Add.
- To modify an existing XML content type, select that type and then click Edit. The Configure Web App Firewall XML Content Type dialog appears. Note: If you select an existing XML content type pattern and then click Add, the dialog box displays the information for that XML content type pattern. You can modify that information to create your new XML content type pattern.
- IsRegex. Select or clear to enable PCRE-format regular expressions in the form field name.
- XML Content Type Enter a literal string or PCRE-format regular expression that matches the XML content type pattern that you want to add.
- Click Create .
- To remove an XML content type pattern from the list, select it, then click Remove to remove it, and then click OK to confirm your choice.
- When you have finished adding and removing XML content type patterns, click Close .
In this article
This Preview product documentation is Citrix Confidential.
You agree to hold this documentation confidential pursuant to the terms of your Citrix Beta/Tech Preview Agreement.
The development, release and timing of any features or functionality described in the Preview documentation remains at our sole discretion and are subject to change without notice or consultation.
The documentation is for informational purposes only and is not a commitment, promise or legal obligation to deliver any material, code or functionality and should not be relied upon in making Citrix product purchase decisions.
If you do not agree, select Do Not Agree to exit.
Machine Translation Feedback Form

The Proper Content Type for XML Feeds
RSS Feeds have a content type problem. Most people end up serving them with the content-type: text/xml . But this practice is frowned upon for several reasons. The main reason people don't like text/xml is because its very vague, there are content types such as application/rss+xml , application/rdf+xml , and application/atom+xml that describe the content of your feed much better than text/xml does. We should be using these types for our feeds.
The problem, however with the more descriptive content types is that Firefox and IE prompt you to download the XML file instead of displaying it in the browser like it would a text/xml document.
So what I have decided to do, is to serve the feeds as text/xml if the user agent contains Mozilla . So for IE, Firefox, and Safari 1.x my feed will be served in text/xml other clients will get the proper application/rss+xml MIME type. Here's my code for this:
I realize that this is not a perfect solution, it may cause browser plugins to have to do some extra work to determine if the document is an RSS, RDF or Atom Feed. Additionally if aggregators are including Mozilla in their user agent, they will get text/xml . But I'm not going to risk loosing potential subscribers over this issue, as some bloggers have reported to be the case when switching.
So I will serve a variable content-type at least until bug 256379 is fixed in a production release of FireFox (or if IE beats them I guess :). You can vote for that bug in bugzilla if you find the save dialog to be annoying when you click on RSS feeds.
I also hope that IE7 is will serve the rss related content-types as it would a text/xml doc by default. Scoble, can you make sure IE7 deals with this? (apparently Robert Scoble will read your post if you put his name in it...)
Tim Bray has pointed out why its important for people to get their act together:
To manage the traffic load we're going to have to do some caching. Fortunately, RSS contains some publication and expiry-date data to help intermediate software do this, but to do this it has to recognize the data as RSS and read this stuff. This isn't going to happen until RSS gets served with the proper Media-type. When someone writes RSS-reader code to live in the Web Browser, it's going to need a consistent Media-type to be able to recognize RSS.
Yet Another Community System cites some of the problems with text/xml such as the character set issues:
The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII or ISO-8859-1 for all MIME types prefixed by text, depending of the Request for Comment you are considering. Of course, having two different specifications is confusing to the software industry. But also, no one of these two charsets can support complex foreign charsets as those used in Asia. On the other hand, implementors and users of XML parsers tend to assume that the default charset is provided by the XML encoding declaration or BOM.
Like this? Follow me ↯
The Proper Content Type for XML Feeds was first published on June 13, 2005.
If you like reading about rss, xml, atom, rdf, content-type, http, mime, firefox, ie, or mozilla then you might also like:
- Foundeo's 2007 End of the Year Sale
- SoloSub is for button addicts
- Finding Feed subscribers from the User Agent
- One liner to download a Browser with PowerShell on Windows Server
- Sessions don't work in Chrome but do in IE
- Ajax Same Origin Policy No More with Firefox 3.5
- Firefox 3.5 Introduces Origin Header, Security Features
- Geolocation API for Adobe AIR?
XML Tutorial
Xpath tutorial, xslt tutorial, xquery tutorial, xsd data types, web services.
XML stands for eXtensible Markup Language.
XML was designed to store and transport data.
XML was designed to be both human- and machine-readable.
XML Example 1
Display the XML File » Display the XML File as a Note »
XML Example 2
Display the XML File » Display with XSLT »
Advertisement
Why Study XML?
XML plays an important role in many different IT systems.
XML is often used for distributing data over the Internet.
It is important (for all types of software developers!) to have a good understanding of XML.
What You Will Learn
This tutorial will give you a solid understanding of:
- What is XML?
- How does XML work?
- How can I use XML?
- What can I use XML for?

Important XML Standards
This tutorial will also dig deep into the following important XML standards:
- XML Services
We recommend reading this tutorial, in the sequence listed in the left menu.
Learn by Examples
Examples are better than 1000 words. Examples are often easier to understand than text explanations.
This tutorial supplements all explanations with clarifying "Try it Yourself" examples.
- XML Examples
- AJAX Examples
- DOM Examples
- XPath Examples
- XSLT Examples
XML Quiz Test
Test your XML skills at W3Schools!
My Learning
Track your progress with the free "My Learning" program here at W3Schools.
Log in to your account, and start earning points!
This is an optional feature. You can study W3Schools without using My Learning.

Kickstart your career
Get certified by completing the course

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
JSON and XML Serialization in ASP.NET Web API
- 9 minutes to read
- 11 contributors
This article describes the JSON and XML formatters in ASP.NET Web API.
In ASP.NET Web API, a media-type formatter is an object that can:
- Read CLR objects from an HTTP message body
- Write CLR objects into an HTTP message body
Web API provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request.
JSON Media-Type Formatter
Read-only properties, camel casing, anonymous and weakly-typed objects, xml media-type formatter, setting per-type xml serializers, removing the json or xml formatter, handling circular object references, testing object serialization.
JSON formatting is provided by the JsonMediaTypeFormatter class. By default, JsonMediaTypeFormatter uses the Json.NET library to perform serialization. Json.NET is a third-party open source project.
If you prefer, you can configure the JsonMediaTypeFormatter class to use the DataContractJsonSerializer instead of Json.NET. To do so, set the UseDataContractJsonSerializer property to true :
JSON Serialization
This section describes some specific behaviors of the JSON formatter, using the default Json.NET serializer. This is not meant to be comprehensive documentation of the Json.NET library; for more information, see the Json.NET Documentation .
What Gets Serialized?
By default, all public properties and fields are included in the serialized JSON. To omit a property or field, decorate it with the JsonIgnore attribute.
If you prefer an "opt-in" approach, decorate the class with the DataContract attribute. If this attribute is present, members are ignored unless they have the DataMember . You can also use DataMember to serialize private members.
Read-only properties are serialized by default.
By default, Json.NET writes dates in ISO 8601 format. Dates in UTC (Coordinated Universal Time) are written with a "Z" suffix. Dates in local time include a time-zone offset. For example:
By default, Json.NET preserves the time zone. You can override this by setting the DateTimeZoneHandling property:
If you prefer to use Microsoft JSON date format ( "\/Date(ticks)\/" ) instead of ISO 8601, set the DateFormatHandling property on the serializer settings:
To write indented JSON, set the Formatting setting to Formatting.Indented :
To write JSON property names with camel casing, without changing your data model, set the CamelCasePropertyNamesContractResolver on the serializer:
An action method can return an anonymous object and serialize it to JSON. For example:
The response message body will contain the following JSON:
If your web API receives loosely structured JSON objects from clients, you can deserialize the request body to a Newtonsoft.Json.Linq.JObject type.
However, it is usually better to use strongly typed data objects. Then you don't need to parse the data yourself, and you get the benefits of model validation.
The XML serializer does not support anonymous types or JObject instances. If you use these features for your JSON data, you should remove the XML formatter from the pipeline, as described later in this article.
XML formatting is provided by the XmlMediaTypeFormatter class. By default, XmlMediaTypeFormatter uses the DataContractSerializer class to perform serialization.
If you prefer, you can configure the XmlMediaTypeFormatter to use the XmlSerializer instead of the DataContractSerializer . To do so, set the UseXmlSerializer property to true :
The XmlSerializer class supports a narrower set of types than DataContractSerializer , but gives more control over the resulting XML. Consider using XmlSerializer if you need to match an existing XML schema.
XML Serialization
This section describes some specific behaviors of the XML formatter, using the default DataContractSerializer .
By default, the DataContractSerializer behaves as follows:
- All public read/write properties and fields are serialized. To omit a property or field, decorate it with the IgnoreDataMember attribute.
- Private and protected members are not serialized.
- Read-only properties are not serialized. (However, the contents of a read-only collection property are serialized.)
- Class and member names are written in the XML exactly as they appear in the class declaration.
- A default XML namespace is used.
If you need more control over the serialization, you can decorate the class with the DataContract attribute. When this attribute is present, the class is serialized as follows:
- "Opt in" approach: Properties and fields are not serialized by default. To serialize a property or field, decorate it with the DataMember attribute.
- To serialize a private or protected member, decorate it with the DataMember attribute.
- Read-only properties are not serialized.
- To change how the class name appears in the XML, set the Name parameter in the DataContract attribute.
- To change how a member name appears in the XML, set the Name parameter in the DataMember attribute.
- To change the XML namespace, set the Namespace parameter in the DataContract class.
Read-only properties are not serialized. If a read-only property has a backing private field, you can mark the private field with the DataMember attribute. This approach requires the DataContract attribute on the class.
Dates are written in ISO 8601 format. For example, "2012-05-23T20:21:37.9116538Z".
To write indented XML, set the Indent property to true :
You can set different XML serializers for different CLR types. For example, you might have a particular data object that requires XmlSerializer for backward compatibility. You can use XmlSerializer for this object and continue to use DataContractSerializer for other types.
To set an XML serializer for a particular type, call SetSerializer .
You can specify an XmlSerializer or any object that derives from XmlObjectSerializer .
You can remove the JSON formatter or the XML formatter from the list of formatters, if you do not want to use them. The main reasons to do this are:
- To restrict your web API responses to a particular media type. For example, you might decide to support only JSON responses, and remove the XML formatter.
- To replace the default formatter with a custom formatter. For example, you could replace the JSON formatter with your own custom implementation of a JSON formatter.
The following code shows how to remove the default formatters. Call this from your Application_Start method, defined in Global.asax.
By default, the JSON and XML formatters write all objects as values. If two properties refer to the same object, or if the same object appears twice in a collection, the formatter will serialize the object twice. This is a particular problem if your object graph contains cycles, because the serializer will throw an exception when it detects a loop in the graph.
Consider the following object models and controller.
Invoking this action will cause the formatter to throw an exception, which translates to a status code 500 (Internal Server Error) response to the client.
To preserve object references in JSON, add the following code to Application_Start method in the Global.asax file:
Now the controller action will return JSON that looks like this:
Notice that the serializer adds an "$id" property to both objects. Also, it detects that the Employee.Department property creates a loop, so it replaces the value with an object reference: {"$ref":"1"}.
Object references are not standard in JSON. Before using this feature, consider whether your clients will be able to parse the results. It might be better simply to remove cycles from the graph. For example, the link from Employee back to Department is not really needed in this example.
To preserve object references in XML, you have two options. The simpler option is to add [DataContract(IsReference=true)] to your model class. The IsReference parameter enables object references. Remember that DataContract makes serialization opt-in, so you will also need to add DataMember attributes to the properties:
Now the formatter will produce XML similar to following:
If you want to avoid attributes on your model class, there is another option: Create a new type-specific DataContractSerializer instance and set preserveObjectReferences to true in the constructor. Then set this instance as a per-type serializer on the XML media-type formatter. The following code show how to do this:
As you design your web API, it is useful to test how your data objects will be serialized. You can do this without creating a controller or invoking a controller action.
Additional resources
- Español – América Latina
- Português – Brasil
- Documentation
- App Engine standard environment
The Deployment Descriptor: web.xml
The REGION_ID is an abbreviated code that Google assigns based on the region you select when you create your app. The code does not correspond to a country or province, even though some region IDs may appear similar to commonly used country and province codes. For apps created after February 2020, REGION_ID .r is included in App Engine URLs. For existing apps created before this date, the region ID is optional in the URL.
Learn more about region IDs .
Java web applications use a deployment descriptor file to determine how URLs map to servlets, which URLs require authentication, and other information. This file is named web.xml , and resides in the app's WAR under the WEB-INF/ directory. web.xml is part of the servlet standard for web applications.
For more information about the web.xml standard, see the Metawerx web.xml reference wiki and the Servlet specification .
web.xml deployment descriptor
A web application's deployment descriptor describes the classes, resources and configuration of the application and how the web server uses them to serve web requests. When the web server receives a request for the application, it uses the deployment descriptor to map the URL of the request to the code that ought to handle the request.
The deployment descriptor is a file named web.xml . It resides in the app's WAR under the WEB-INF/ directory. The file is an XML file whose root element is <web-app> .
Here is a simple web.xml example that maps all URL paths ( /* ) to the servlet class mysite.server.ComingSoonServlet :
Servlets and URL paths
web.xml defines mappings between URL paths and the servlets that handle requests with those paths. The web server uses this configuration to identify the servlet to handle a given request and call the class method that corresponds to the request method. For example: the doGet() method for HTTP GET requests.
To map a URL to a servlet, you declare the servlet with the <servlet> element, then define a mapping from a URL path to a servlet declaration with the <servlet-mapping> element.
The <servlet> element declares the servlet, including a name used to refer to the servlet by other elements in the file, the class to use for the servlet, and initialization parameters. You can declare multiple servlets using the same class with different initialization parameters. The name for each servlet must be unique across the deployment descriptor.
The <servlet-mapping> element specifies a URL pattern and the name of a declared servlet to use for requests whose URL matches the pattern. The URL pattern can use an asterisk ( * ) at the beginning or end of the pattern to indicate zero or more of any character. The standard does not support wildcards in the middle of a string, and does not allow multiple wildcards in one pattern. The pattern matches the full path of the URL, starting with and including the forward slash ( / ) following the domain name. The URL path cannot start with a period ( . ).
With this example, a request for the URL http://www.example.com/blue/teamProfile is handled by the TeamServlet class, with the teamColor parameter equal to blue and the bgColor parameter equal to #0000CC . The servlet can get the portion of the URL path matched by the wildcard using the ServletRequest object's getPathInfo() method.
The servlet can access its initialization parameters by getting its servlet configuration using its own getServletConfig() method, then calling the getInitParameter() method on the configuration object using the name of the parameter as an argument.
An app can use JavaServer Pages (JSPs) to implement web pages. JSPs are servlets defined using static content, such as HTML, mixed with Java code.
App Engine supports automatic compilation and URL mapping for JSPs. A JSP file in the application's WAR (outside of WEB-INF/ ) whose filename ends in .jsp is compiled into a servlet class automatically, and mapped to the URL path equivalent to the path to the JSP file from the WAR root. For example, if an app has a JSP file named start.jsp in a subdirectory named register/ in its WAR, App Engine compiles it and maps it to the URL path /register/start.jsp .
If you want more control over how the JSP is mapped to a URL, you can specify the mapping explicitly by declaring it with a <servlet> element in the deployment descriptor. Instead of a <servlet-class> element, you specify a <jsp-file> element with the path to the JSP file from the WAR root. The <servlet> element for the JSP can contain initialization parameters.
You can install JSP tag libraries with the <taglib> element. A tag library has a path to the JSP Tag Library Descriptor (TLD) file ( <taglib-location> ) and a URI that JSPs use to select the library for loading ( <taglib-uri> ). Note that App Engine provides the JavaServer Pages Standard Tag Library (JSTL), and you do not need to install it.
Security and authentication
An App Engine application can use Google Accounts for user authentication. The app can use the Google Accounts API to detect whether the user is signed in, get the currently signed-in user's email address, and generate sign-in and sign-out URLs. An app can also specify access restrictions for URL paths based on Google Accounts, using the deployment descriptor.
The <security-constraint> element defines a security constraint for URLs that match a pattern. If a user accesses a URL whose path has a security constraint and the user is not signed in, App Engine redirects the user to the Google Accounts sign-in page. Google Accounts redirects the user back to the application URL after successfully signing in or registering a new account. The app does not need to do anything else to ensure that only signed-in users can access the URL.
A security constraint includes an authorization constraint that specifies which Google Accounts users can access the path. If the authorization constraint specifies a user role of * , then any users signed in with a Google Account can access the URL. If the constraint specifies a user role of admin , then only registered developers of the application can access the URL. The admin role makes it easy to build administrator-only sections of your site.
App Engine does not support custom security roles ( <security-role> ) or alternate authentication mechanisms ( <login-config> ) in the deployment descriptor.
Security constraints apply to static files as well as servlets.
Secure URLs
Google App Engine supports secure connections via HTTPS for URLs using the REGION_ID .r.appspot.com domain. When a request accesses a URL using HTTPS, and that URL is configured to use HTTPS in the web.xml file, both the request data and the response data are encrypted by the sender before they are transmitted, and decrypted by the recipient after they are received. Secure connections are useful for protecting customer data, such as contact information, passwords, and private messages.
To declare that HTTPS should be used for a URL, you set up a security constraint in the deployment descriptor (as described in Security and authentication ) with a <user-data-constraint> whose <transport-guarantee> is CONFIDENTIAL . For example:
Requests using HTTP (non-secure) for URLs whose transport guarantee is CONFIDENTIAL are automatically redirected to the same URL using HTTPS.
Any URL can use the CONFIDENTIAL transport guarantee, including JSPs and static files.
The development web server does not support HTTPS connections. It ignores the transport guarantee, so paths intended for use with HTTPS can be tested using regular HTTP connections to the development web server.
When you test your app's HTTPS handlers using the versioned appspot.com URL, such as https://1.latest. your_app_id . REGION_ID .r.appspot.com/ , your browser warns you that the HTTPS certificate was not signed for that specific domain path. If you accept the certificate for that domain, pages will load successfully. Users will not see the certificate warning when accessing https:// your_app_id . REGION_ID .r.appspot.com/ .
You can also use an alternate form of the versioned appspot.com URL designed to avoid this problem by replacing the periods separating the subdomain components with the string " -dot- ". For instance, the previous example could be accessed without a certificate warning at https:// VERSION_ID -dot-default-dot- PROJECT_ID . REGION_ID .r.appspot.com .
Google Accounts sign-in and sign-out are always performed using a secure connection and is unrelated to how the application's URLs are configured.
As mentioned above, security constraints apply to static files as well as servlets. This includes the transport guarantee.
Note: Google recommends using the HTTPS protocol to send requests to your app. Google does not issue SSL certificates for double-wildcard domains hosted at appspot.com . Therefore with HTTPS you must use the string "-dot-" instead of "." to separate subdomains, as shown in the examples below. You can use a simple "." with your own custom domain or with HTTP addresses. For more information, see HTTPS as a ranking signal .
The welcome file list
When the URLs for your site represent paths to static files or JSPs in your WAR, it is often a good idea for paths to directories to do something useful as well. A user visiting the URL path /help/accounts/password.jsp for information on account passwords might try to visit /help/accounts/ to find a page introducing the account system documentation. The deployment descriptor can specify a list of filenames that the server should try when the user accesses a path that represents a WAR subdirectory that is not already explicitly mapped to a servlet. The servlet standard calls this the "welcome file list."
For example, if the user accesses the URL path /help/accounts/ , the following <welcome-file-list> element in the deployment descriptor tells the server to check for help/accounts/index.jsp and help/accounts/index.html before reporting that the URL does not exist:
A filter is a class that acts on a request like a servlet, but can allow the handling of the request to continue with other filters or servlets. A filter may perform an auxiliary task, such as logging, performing specialized authentication checks, or annotating the request or response objects before calling the servlet. Filters allow you to compose request processing tasks from the deployment descriptor.
A filter class implements the javax.servlet.Filter interface, including the doFilter() method. Here is a simple filter implementation that logs a message, and passes control down the chain, which may include other filters or a servlet, as described by the deployment descriptor:
Similar to servlets, you configure a filter in the deployment descriptor by declaring the filter with the <filter> element, then mapping it to a URL pattern with the <filter-mapping> element. You can also map filters directly to other servlets.
The <filter> element contains a <filter-name> , <filter-class> , and optional <init-param> elements.
The <filter-mapping> element contains a <filter-name> that matches the name of a declared filter, and either a <url-pattern> element for applying the filter to URLs, or a <servlet-name> element that matches the name of a declared servlet for applying the filter whenever the servlet is called.
Error Handlers
You can customize what the server sends to the user when an error occurs, using the deployment descriptor. The server can display an alternate page location when it's about to send a particular HTTP status code, or when a servlet raises a particular Java exception.
The <error-page> element contains either an <error-code> element with an HTTP error code value (such as 500 ), or an <exception-type> element with the class name of the expected exception (such as java.io.IOException ). It also contains a <location> element containing the URL path of the resource to show when the error occurs.
Unsupported web.xml features
The following web.xml features are not supported by App Engine:
- App Engine supports the <load-on-startup> element for servlet declarations. However, the load actually occurs during the first request handled by the web server instance, not prior to it.
- Some deployment descriptor elements can take a human readable display name, description and icon for use in IDEs. App Engine doesn't use these, and ignores them.
- App Engine doesn't support JNDI environment variables ( <env-entry> ).
- App Engine doesn't support EJB resources ( <resource-ref> ).
- Notification of the destruction of servlets, servlet context, or filters is not supported.
- The <distributable> element is ignored.
- Servlet scheduling with <run-at> is not supported.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2023-03-10 UTC.

IMAGES
VIDEO
COMMENTS
Using web.xml, you can assign custom URLs for invoking servlets, specify initialization parameters for the entire application as well as for specific servlets, control session timeouts, declare filters, declare security roles, restrict access to Web resources based on declared security roles, and so on. Share Follow answered Aug 23, 2014 at 14:32
The web.xml file provides configuration and deployment information for the web components that comprise a web application.. The Java™ Servlet specification defines the web.xml deployment descriptor file in terms of an XML schema document. For backwards compatibility, any web.xml file that is written to Servlet 2.2 or ater that worked in previous versions of WebSphere® Application Server are ...
Content-Type The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending). In responses, a Content-Type header provides the client with the actual content type of the returned content.
To remove the String, you'll have to make the return parameter xml like this: public **System.Xml.XmlDocument** MyFunc (string xmlRequest) This will make the response become; HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> xml Share Improve this answer Follow
It is also much more easily rendered in multiple formats, e.g., Web, XML, mobile device-friendly, or PDF for print. ... Step 1: At content creation (new webpages) or when reviewing existing content that has not had type assigned, assign web content one of the following types, described in the Web Content Types and Review Schedule table below ...
To post XML to the server, you need to make an HTTP POST request, include the XML data in the body of the POST request message, and set the correct MIME type for the XML using the "Content-Type: application/xml" HTML header. Optionally, you can send an "Accept: application/xml" request header that will tell the server that the client is ...
We can easily configure our Web API to provide and receive data in XML format The Accept header is used to indicate the media type we accept as a response (this can be JSON, XML, among others) Content negotiation refers to the process of determining the best content format for a given request
Content-Type := type "/" subtype * [";" parameter] type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token x-token := < The two characters "X-" followed, with no intervening white space, by any token > subtype := token parameter := attribute "=" value attribute := token value := token / quoted-string
To configure the XML content type list by using the GUI Navigate to Security > Web App Firewall. In the details pane, under Settings, click Manage XML Content Types. In the Manage XML Content Types dialog box, do one of the following: To add a new XML content type, click Add.
A SOAP message is an ordinary XML document containing the following elements: An Envelope element that identifies the XML document as a SOAP message. A Header element that contains header information. A Body element that contains call and response information. A Fault element containing errors and status information.
Visual Studio uses the [Content_Types].xml file to install the package, but it does not install the file itself. Note Although this topic applies only to [Content_Type].xml files that are used in VSIX packages, the [Content_Types].xml file type is part of the Open Packaging Conventions (OPC) standard.
When someone writes RSS-reader code to live in the Web Browser, it's going to need a consistent Media-type to be able to recognize RSS. ... The Proper Content Type for XML Feeds was first published on June 13, 2005. If you like reading about rss, xml, atom, rdf, content-type, http, mime, firefox, ie, or mozilla then you might also like:
XML can be generated from a database without any installed XML software. To generate an XML database response from the server, simply write the following code and save it as an ASP file on the web server: <%. response.ContentType = "text/xml". set conn=Server.CreateObject ("ADODB.Connection")
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
Even removed the expected content-type. I'm getting a 400 Bad Request response from Fiddler that way and my breakpoint inside the function does not get triggered. Maybe there is an issue with my request settings? I only changed Content-Type from application/xml to text/xml;charset=utf-8 or text/xml since it worked with the first method.
The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should be followed and not be changed. The header allows you to avoid MIME type sniffing by saying that the MIME types are deliberately configured.
Web API provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request. Contents JSON Media-Type Formatter Read-Only Properties Dates Indenting Camel Casing Anonymous and Weakly-Typed Objects
web.xml defines mappings between URL paths and the servlets that handle requests with those paths. The web server uses this configuration to identify the servlet to handle a given request and...