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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T01:18:27+00:00 2026-05-23T01:18:27+00:00

I am creating a REST API in ASP.NET MVC. I want the format of

  • 0

I am creating a REST API in ASP.NET MVC. I want the format of the request and response to be JSON or XML, however I also want to make it easy to add another data format and easy to create just XML first and add JSON later.

Basically I want to specify all of the inner workings of my API GET/POST/PUT/DELETE requests without having to think about what format the data came in as or what it will leave as and I could easily specify the format later or change it per client. So one guy could use JSON, one guy could use XML, one guy could use XHTML. Then later I could add another format too without having to rewrite a ton of code.

I do NOT want to have to add a bunch of if/then statements to the end of all my Actions and have that determine the data format, I’m guessing there is some way I can do this using interfaces or inheritance or the like, just not sure the best approach.

  • 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-23T01:18:28+00:00Added an answer on May 23, 2026 at 1:18 am

    Serialization

    The ASP.NET pipeline is designed for this. Your controller actions don’t return the result to the client, but rather a result object (ActionResult) which is then processed in further steps in the ASP.NET pipeline. You can override the ActionResult class. Note that FileResult, JsonResult, ContentResult and FileContentResult are built-in as of MVC3.

    In your case, it’s probably best to return something like a RestResult object. That object is now responsible to format the data according to the user request (or whatever additional rules you may have):

    public class RestResult<T> : ActionResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            string resultString = string.Empty;
            string resultContentType = string.Empty;
    
            var acceptTypes = context.RequestContext.HttpContext.Request.AcceptTypes;
    
            if (acceptTypes == null)
            {
                resultString = SerializeToJsonFormatted();
                resultContentType = "application/json";
            }
            else if (acceptTypes.Contains("application/xml") || acceptTypes.Contains("text/xml"))
            {
                resultString = SerializeToXml();
                resultContentType = "text/xml";
            }
    
           context.RequestContext.HttpContext.Response.Write(resultString);
            context.RequestContext.HttpContext.Response.ContentType = resultContentType;
       }
    }
    

    Deserialization

    This is a bit more tricky. We’re using a Deserialize<T> method on the base controller class. Please note that this code is not production ready, because reading the entire response can overflow your server:

    protected T Deserialize<T>()
    {
        Request.InputStream.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(Request.InputStream);
        var rawData = sr.ReadToEnd(); // DON'T DO THIS IN PROD!
    
        string contentType = Request.ContentType;
    
        // Content-Type can have the format: application/json; charset=utf-8
        // Hence, we need to do some substringing:
        int index = contentType.IndexOf(';');
        if(index > 0)
            contentType = contentType.Substring(0, index);
        contentType = contentType.Trim();
    
        // Now you can call your custom deserializers.
        if (contentType == "application/json")
        {
            T result = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(rawData);                
            return result;
        }
        else if (contentType == "text/xml" || contentType == "application/xml")
        {
            throw new HttpException(501, "XML is not yet implemented!");
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am creating a simple REST API that outputs JSON data. However I am
I'm creating REST service using ASP.NET Web API. How can I return 401 status
I'm creating a JSON REST API (lots of caps there), and already have Data.Aeson.Generic
We are creating ReST Web Services using ASP.NET and OpenRasta. Is there any tool
I am creating my first ASP.NET MVC 3 application, and my data comes from
I'm working on creating a REST API. Lets say the resource I'm serving is
I'm writing a library that wraps around a REST API. The wrapper I'm creating
I am in need of creating a rest api for syncing data with my
I am creating a Windows 7 mobile Silverlight project. I use Rest api for
I am in the process of creating a RESTful API. I read http://microformats.org/wiki/rest/urls but

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.