我的 config.Routes 设置为:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
有了这个我可以使用:
localhost:port/api/products
- 获取完整的产品列表localhost:port/api/products/#
- 获取具有给定 id 的单个产品
基于浏览器,我获得了不同的格式(在 FireFox 和 Google Chrome 中默认为 XML 格式,在 Internet Explorer 中为 JSON)。
我主要需要JSON,所以一开始我补充说:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
所以我的回复将始终采用 JSON 格式。
此时一切都按预期进行,我在上面提到的两个 GET 请求上收到了 JSON 格式的响应。
然后我偶然发现了 this stackoverflow post . 认为根据 GET 请求为自己选择要返回的格式会是一个很好的功能。
但是,当我替换上面提到的 config.Routes 和 JSON-only 代码时:
config.Routes.MapHttpRoute(
name: "API UriPathExtentsion",
routeTemplate: "api/{controller}.{ext}/{id}",
defaults: new { id = RouteParameter.Optional, ext = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "API UriPathExtension ID",
routeTemplate: "api/{controller}/{id}.{ext}",
defaults: new { id = RouteParameter.Optional, ext = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
我收到以下 404 错误:
在 localhost:post/api/products
上:
在 localhost:port/api/products.xml
上:
有人知道哪里出了问题吗?
此外,我不确定第二段代码是否会完全按照我的意愿执行,因此这里是示例请求列表以及我希望它返回的内容:
localhost:port\api\products
- 获取默认浏览器格式的产品列表localhost:port\api\products\#
- 以默认浏览器格式获取单个产品localhost:port\api\products.xml
- 获取 XML 格式的产品列表localhost:port\api\products.json
- 获取 JSON 格式的产品列表localhost:port\api\products\#.xml
- 获取 XML 格式的单个产品localhost:port\api\products\#.json
- 获取 JSON 格式的单个产品
预先感谢您的回复。
编辑 1:在评论后将 exten
更改为 ext
。仍然是同样的错误..
最佳答案
您链接到的帖子说:
Remember in this example, you still have to issue the request with the appropriate content-type.
这意味着调用您的 API 的任何人都需要将内容类型设置为匹配 application/json
或 text/xml
。如果您从浏览器调用,您的内容类型将是您正在使用的浏览器的默认内容类型,很可能是 text/plain
。
选项 1:谷歌并找出如何更改您正在使用的浏览器的内容类型。我自己从未尝试过改变这一点。
选项 2:如果您从代码调用它并使用 C#,请使用 HttpClient
并在调用前修改内容类型,如 this StackOverflow post 中所述。 .
选项 3:使用 Fiddler (free) 中的 Composer 调用您的服务。在那里很容易设置内容类型。在测试 Web API 时,我更喜欢这个。
说完所有这些之后,我不确定这是否真的解决了您的问题,但我希望如此。至少你然后按照你链接到的帖子所说的一切。祝你好运!
关于C# Web API 基于 GET 请求的 XML 或 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23366755/