c# - 根据请求从 MVC web api 返回 xml 或 json

标签 c# asp.net-mvc asp.net-web-api asp.net-mvc-routing wcf-web-api

给定以下 webapiconfig;

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

和这个 Controller ;

  public class ProductsController : ApiController
    {
         Product[] _products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return _products;
        }
    }

使用 URL http://localhost/api/Products 我得到了 XML 格式的产品列表。

我想做的是根据请求选择返回 json 或 xml。所以对于 json,它将是;

http://localhost/api/Products.json

对于 XML,它将是;

http://localhost/api/Products.xml

同样;

http://localhost/api/Products.json/1/
http://localhost/api/Products.xml/1/

这可能吗?我将如何实现此功能?

另一种选择是;

http://localhost/api/json/Products/

最佳答案

是的,您可以使用 AddUriPathExtensionMapping

你可以这样创建路由:

routes.MapHttpRoute(
  name: "Api UriPathExtension",
  routeTemplate: "api/{controller}.{extension}/{id}",
  defaults: new { id = RouteParameter.Optional, extension = RouteParameter.Optional }
);

routes.MapHttpRoute(
  name: "Api UriPathExtension ID",
  routeTemplate: "api/{controller}/{id}.{extension}",
  defaults: new { id = RouteParameter.Optional, extension = RouteParameter.Optional }
); 

然后你需要扩展格式化程序:

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

确保添加对 System.Net.Http.Formatting 的引用,因为这些方法是扩展方法,默认情况下智能感知不会看到它们。

请记住,在此示例中,您仍然必须使用适当的内容类型发出请求。但是,如果您希望通过浏览器地址栏直接获得这些内容,您可以映射到“text/html”。

我不久前写了一篇关于所有这些的博客文章 - 这应该会有所帮助,并带您了解更多详细信息 http://www.strathweb.com/2012/04/different-mediatypeformatters-for-same-mediaheadervalue-in-asp-net-web-api/

关于c# - 根据请求从 MVC web api 返回 xml 或 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13053485/

相关文章:

c# - 使用 DirectoryServices 进行跨域身份验证

c# - Prism 请求导航到新 View

c# - 无法检查请求中 header 值的空值

javascript - 加载 Javascript 文件的问题

jquery - mvc 下拉菜单更改不触发 jquery

c# - 使用 JSON.net 将枚举容器序列化为字符串

asp.net-web-api - 修改WebApi DelegatingHandler中的Request.Content

c# - Microsoft JScript 运行时错误 : Object doesn't support this property or method

javascript - 将 jQuery (Json) 中的日期时间附加到表中

c# - MVC 获取与发布