Shilpa Nagavara
Shilpa Nagavara

Reputation: 1165

ASP.Net WebApi: return data in json and xml formats

My ASP.Net WebAPI needs to return data that can be consumed in XML or Json format. The get method returns an object that contains objects of other types and hence the Data attribute in the Response class is defined as object.

Response class

public class Response
{
    public int StatusCode { get; set; }

    public string StatusMessage { get; set; }

    public object Data { get; set; }
}

This throws an error while accepting data in XML format

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

However, when I change the type of Data attributed to strongly typed such as IList, it returns data in json and xml format just fine.

I need the Response class to be generic so I can reuse it for multiple controllers and action. How can I achieve this?

Upvotes: 2

Views: 8963

Answers (3)

Anton Anpilogov
Anton Anpilogov

Reputation: 141

Or you can manage it by yourself.

    [HttpGet]
    [Auth(Roles = "User")]
    public HttpResponseMessage Get(Guid id, [FromUri]string format = "json")
    {
            Guid userGuid = GetUserID(User as ClaimsPrincipal);                

            HttpStatusCode sc = HttpStatusCode.OK;
            string sz = "";

            try
            {
                sz = SerializationHelper.Serialize(format, SomeDataRepository.GetOptions(id, userGuid));
            }
            catch (Exception ex)
            {
                sc = HttpStatusCode.InternalServerError;
                sz = SerializationHelper.Serialize(format,
                                                   new ApiErrorMessage("Error occured",
                                                                       ex.Message));
            }

            var res = CreateResponse(sc);
            res.Content = new StringContent(sz, Encoding.UTF8, string.Format("application/{0}", format));

            return res;            
    }

You can pass format from parameters or you can read it from request headers. Also you can use StreamContent instead StringContent cause serializers like StackTrace and Newtosnoft.Json can handle it.

Upvotes: 2

Marcus Höglund
Marcus Höglund

Reputation: 16801

One way to handle this is to use AddUriPathExtensionMapping in the route configuration

In the WebApiConfig.cs

config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{format}/{id}",
    defaults: new { format= RouteParameter.Optional, id = RouteParameter.Optional }
);

//Uri format config
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

Then when you call the api you define which format the response should be in the url

http://yourdomain.com/api/controller/xml 
http://yourdomain.com/api/controller/json 

Upvotes: 1

Shilpa Nagavara
Shilpa Nagavara

Reputation: 1165

This was a rather circuitous approach I was taking. Instead of returning the response object, I am returning HttpResponse like so

return Request.CreateResponse(HttpStatusCode.OK, terms);

Upvotes: 0

Related Questions