Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16300

WebApi force action to return xml

I have this action:

public IHttpActionResult SearchFor(int aboItemType, DTO.FilterColumns filter)
{
    //Do stuff...
    return Ok<DataSet>(ds);
}

My client does:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

var response = client.PostAsJsonAsync(myurl).Result;
if (response.IsSuccessStatusCode)
{
    var results = HttpUtility.HtmlDecode(response.Content.ReadAsStringAsync().Result);
}

The above scenario works perfectly. However, if I comment the Accept line, the action returns the dataset in json format.

I would like to force this one particular action to always send the result in xml. Is this possible? Maybe with an attribute?

Upvotes: 11

Views: 14078

Answers (2)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

Also you can do this (in the case you have to pass some http header values):

public IHttpActionResult Get()
{
    var result = Request.CreateResponse(HttpStatusCode.OK, 
                                        model,
                                        Configuration.Formatters.XmlFormatter);

    result.Headers.Add("Access-Control-Allow-Origin", "*");

    return ResponseMessage(result);
}

Upvotes: 1

Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

I used Сonfiguration.Formatters.XmlFormatter

public IHttpActionResult Get()
{
 ...
  return Content(HttpStatusCode.OK, Model, Configuration.Formatters.XmlFormatter);
}

Upvotes: 33

Related Questions