相同的 Web API 返回多种格式

时间:2021-07-19 05:39:16

标签: c# asp.net-web-api

我正在开发一个 Asp.Net Web API 项目,我需要以某种方式创建它,以便 2 个不同的客户端可以使用它并获得所需格式的响应。

需要同时支持 JSON 和 XML 格式。

我在 WebApiConfig 文件中的 Register 方法中尝试了一些东西:

public static void Register(HttpConfiguration config)  
{  
    // Adding formatter for Json   
    config.Formatters.JsonFormatter.MediaTypeMappings.Add(  
        new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));  
      
    // Adding formatter for XML   
    config.Formatters.XmlFormatter.MediaTypeMappings.Add(  
        new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));  
}  

这里客户端可以使用 API,但需要传递查询字符串 type=json 或 xml 以获得所需格式的响应。

http://localhost:1312/api/Blog?type=xml
http://localhost:1312/api/Blog?type=json 

有没有更好的方法来检测客户所需的格式并做出相应的响应?如果我们从请求头或类似的东西中得到它,TIA。

1 个答案:

答案 0 :(得分:1)

Asp.net package JsonToJava.test; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsontoJava { public static void main( String[] args ) throws JsonMappingException, JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); try { Data[] dataObj = mapper.readValue(new File("data/sample_array_data.json"), Data[].class); for (Data data: dataObj) { System.out.println("Track Name--->"+data.getName()); System.out.println("Printing Elements--->"+data.getElements()); System.out.println("------------------------"); } } catch (JsonMappingException e) { e.printStackTrace(); }catch (JsonProcessingException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } } 自动执行此操作

例如:

enter image description here

然后像这样添加ApiController标题

enter image description here