基于URL请求返回JSON与XML格式的ASP.NET Web API实现问询
实现ASP.NET Web API按URL后缀返回JSON/XML格式数据
嘿,这事儿不难!你已经搞定了从数据库取Person数据的核心逻辑,只需要调整下Web API的路由和格式映射配置,就能实现按URL后缀返回JSON/XML的需求,具体步骤如下:
1. 修改Web API路由配置
首先要让Web API能识别URL里的.Json/.XML后缀,我们需要在App_Start/WebApiConfig.cs里添加支持格式后缀的路由规则:
using System.Web.Http; namespace SoftAPI { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 优先匹配带格式后缀的URL config.Routes.MapHttpRoute( name: "DefaultApiWithFormat", routeTemplate: "api/{controller}.{format}/{id}", defaults: new { id = RouteParameter.Optional } ); // 保留默认路由(兼容不带后缀的请求,可选) config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // 其他原有配置... } } }
2. 配置URL后缀与媒体类型的映射
接下来要告诉Web API,把.Json后缀对应到JSON格式,.XML对应到XML格式,同样在WebApiConfig.cs的Register方法里添加以下代码:
// 配置URL后缀与媒体类型的映射 config.Formatters.JsonFormatter.MediaTypeMappings.Add( new System.Net.Http.Formatting.UriPathExtensionMapping("json", "application/json")); config.Formatters.XmlFormatter.MediaTypeMappings.Add( new System.Net.Http.Formatting.UriPathExtensionMapping("xml", "application/xml"));
3. 完善你的Person控制器
你的控制器逻辑基本不用大改,只要确保Action返回IHttpActionResult(比如Ok()),Web API就会自动根据URL后缀序列化数据。结合你提供的代码,完善后的控制器示例如下:
using System.Net; using System.Net.Http; using System.Web.Http; using System.Collections.Generic; using System.Linq; namespace SoftAPI.Controllers { public class PersonController : ApiController { // 替换成你实际从数据库获取数据的方法 private IEnumerable<Person> FetchPersonsFromDatabase() { // 这里模拟数据库数据,你可以换成EF或其他数据访问逻辑 return new List<Person> { new Person { Id = 1, Name = "Alice", Age = 29 }, new Person { Id = 2, Name = "Bob", Age = 32 } }; } // GET api/Person.Json 或 api/Person.XML public IHttpActionResult Get() { var persons = FetchPersonsFromDatabase(); return Ok(persons); // 自动根据格式后缀序列化 } // GET api/Person.Json/1 或 api/Person.XML/1 public IHttpActionResult Get(int id) { var person = FetchPersonsFromDatabase().FirstOrDefault(p => p.Id == id); if (person == null) { return NotFound(); } return Ok(person); } } // 你的Person实体类(根据数据库模型调整字段) public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } }
测试验证
现在启动你的Web API项目:
- 访问
http://localhost:15827/api/Person.Json会返回JSON格式的Person列表 - 访问
http://localhost:15827/api/Person.XML会返回XML格式的Person列表 - 单个数据访问比如
http://localhost:15827/api/Person.Json/1也能正常返回对应格式的单条Person数据
内容的提问来源于stack exchange,提问作者Sachith Wickramaarachchi
相关产品推荐
相关产品推荐

