WebAPI to Return XML

前端 未结 5 1746
挽巷
挽巷 2020-11-28 07:34

I\'m wanting my WEB API method to return an XML object back to the calling application. Currently it\'s just returning the XML as a string object. Is this a no no? If so how

5条回答
  •  时光取名叫无心
    2020-11-28 07:53

    You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

    If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

    Accept: application/xml
    

    You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

    EDIT: based on your edited question with code:

    Simple return list of string, instead of converting it to XML. try it using Fiddler.

    public List Get(int tenantID, string dataType, string ActionName)
        {
           List SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
           return SQLResult;
         }
    

    For example if your list is like:

    List list = new List();
    list.Add("Test1");
    list.Add("Test2");
    list.Add("Test3");
    return list;
    

    and you specify Accept: application/xml the output will be:

    
      Test1
      Test2
      Test3
    
    

    and if you specify 'Accept: application/json' in the request then the output will be:

    [
      "Test1",
      "Test2",
      "Test3"
    ]
    

    So let the client request the content type, instead of you sending the customized xml.

提交回复
热议问题