gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:18:59 25 4
gpt4 key购买 nike

给定以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com