0

Could not find any related online source to get the xml result, tried format filter but getting error

Need to return xml like this

<?xml version="1.0" encoding="UTF-8"?>
<BESAPI
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="BESAPI.xsd">
  <Query Resource="(names of it, ids of it, last report time of it) of bes computers whose(id of it=123)">
    <Result>
      <Tuple>
        <Answer type="string">abc</Answer>
        <Answer type="integer">123</Answer>
        <Answer type="time">Mon, 14 Dec 2020 19:34:42 -0700</Answer>
      </Tuple>
    </Result>
    <Evaluation>
      <Time>0.160ms</Time>
      <Plurality>Plural</Plurality>
    </Evaluation>
  </Query>
</BESAPI>

API function:

 // GET api/Test/BigFixSelect
        [HttpGet("BigFixSelect/{computerName}")]
        public HttpResponseMessage TestBigFixSelect(string computerName)
        {
            try
            {
                string date = DateTime.UtcNow.ToString();
                _logger.LogInformation("TestBigFixServer with '{0}' Initiated on '{1}'", computerName, date);

                string XML = $"<BESAPI><Query><Result><Tuple><Answer type=string>{computerName}</Answer><Answer type=time>{date}</Answer></Tuple></Result></Query></BESAPI>";
                return new HttpResponseMessage()
                {
                    Content = new StringContent(XML, Encoding.UTF8, "application/xml")
                };
            }
            catch (Exception ex)
            {
                string XML = $"<note><body>Bad Request</body></note>";
                return new HttpResponseMessage()
                {
                    Content = new StringContent(XML, Encoding.UTF8, "application/xml")
                };
            }
        }

Current return result:

{
  "version": {
  ...
  },
  "content": {
   ...
  },
  "statusCode": 200,
  "reasonPhrase": "OK",
  "headers": [],
  "trailingHeaders": [],
  "requestMessage": null,
  "isSuccessStatusCode": true
}

None of the result has the return detail from my string content, I am new to this not sure if this is totally a wrong way of doing it or just missing out something.

I'm calling the action from PowerShell with :

Invoke-RestMethod -Headers $headers -Method GET -Uri $URL with $headers.Add('Accept','application/xml') 
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Alois
  • 130
  • 1
  • 2
  • 14
  • Does this answer your question? [WebAPI to Return XML](https://stackoverflow.com/questions/11662028/webapi-to-return-xml) – Liam Jul 01 '21 at 10:39
  • 2
    The **client** needs to request XML using the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) – Liam Jul 01 '21 at 10:40
  • 1
    `Could not find any related online source` when that happens, it's always because one is looking for the wrong thing. Formatting the output is the job of ASP.NET itself. When your return an object directly, the runtime will serialize it to *whatever format the client requested* as long as the proper formatter is registered. If the client asks for JSON, they get JSON. If they ask for XML or text, they get that format. So instead of trying to serialize to XML by hand, first ensure the *client* requests XML in the `Accept` header – Panagiotis Kanavos Jul 01 '21 at 10:40
  • @Liam Yes the second method on this post is what I tried, but the result is totally different – Alois Jul 01 '21 at 10:41
  • 1
    @Alois what second method? The *correct* method is to use no extra code, and make sure `Accept` actually requests XML. The code you posted doesn't return any objects, it tries to create and return a string. Did you try to just create and return the *object* you want? – Panagiotis Kanavos Jul 01 '21 at 10:44
  • @Alois btw returning XML *is* documented. If you google for `Web API XML` you'll find [JSON and XML Serialization in ASP.NET Web API](https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization#xml-media-type-formatter). For ASP.NET Core, [Format response data in ASP.NET Core Web API](https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0) – Panagiotis Kanavos Jul 01 '21 at 10:45
  • @Alois the XML formatter may not be registered by default in later ASP.NET Core versions, simply because it's not that common any more. I'm not sure because I haven't had to return XML in almost 10 yeas (except for WCF services). In that case you can [add it back](https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0#add-xml-format-support). Which ASP.NET version are you using? – Panagiotis Kanavos Jul 01 '21 at 10:48
  • @PanagiotisKanavos The second method I meant was from Liam's link. Yes this function is to mimic the xml response for testing purpose, so I actually can hardcode the return value, but needs to be in xml format. I am calling this API from PowerShell Invoke-RestMethod -Headers $headers -Method GET -Uri $URL with $headers.Add('Accept','application/xml') – Alois Jul 01 '21 at 10:49
  • @PanagiotisKanavos I'm using .net 5 – Alois Jul 01 '21 at 10:52
  • @Alois again, you don't need any specific code. You need to *remove* all that code and just return the object you want. ASP.NET will serialize it to JSON or XML. If you do that, you'll get what you request. In ASP.NET Core 5 you probably need to add `services.AddControllers().AddXmlSerializerFormatters();` – Panagiotis Kanavos Jul 01 '21 at 10:53
  • @PanagiotisKanavos in that case, how should I format my current code to get it return with the xml example above provided the correct headers are set? Where should I add this formatters to? – Alois Jul 01 '21 at 10:55
  • @Alois your action should be something like `public MyBesApiDtoTestBigFixSelect(string computerName){ ...; return new MyBesApiDto(....);`. No need for manual serialization. Make sure you have `services.AddControllers().AddXmlSerializerFormatters();` in `Startup` – Panagiotis Kanavos Jul 01 '21 at 10:56
  • 2
    @Alois `Where should I add this formatters to` I already posted the links to the docs. [Format response data in ASP.NET Core Web API](https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0) is the main article. [Add XML Format Support](https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0#add-xml-format-support) shows how to add the XML formatters – Panagiotis Kanavos Jul 01 '21 at 10:58

0 Answers0