请求提供ASP.NET Web API 2.0接口仅返回JSON格式的代码修改方案
Hey there, let's get your GetPartnerList method to only return JSON in ASP.NET Web API 2.0. I've got a couple of straightforward approaches for you, depending on whether you want this behavior just for this single method or across your entire API.
1. 直接在方法中返回JSON(单方法生效)
Instead of returning a List<Partner> directly, change the return type to IHttpActionResult and wrap your result with the Json() helper method. This explicitly tells Web API to serialize the response as JSON, regardless of what the request headers specify.
Here's the modified code:
public async Task<IHttpActionResult> GetPartnerList() { var partnerList = await _context.Partners.Take(100).ToListAsync(); return Json(partnerList); }
2. 使用[Produces]特性(单方法/控制器生效)
You can add the [Produces] attribute to either the specific method or the entire controller to enforce JSON output. This is great if you want to set this rule for a subset of your API endpoints.
单方法示例:
[Produces("application/json")] public async Task<List<Partner>> GetPartnerList() { return await _context.Partners.Take(100).ToListAsync(); }
整个控制器示例:
Just add the attribute to the controller class, and all methods in it will return JSON by default:
[Produces("application/json")] public class YourPartnerController : ApiController { // Your methods here... }
3. 全局配置(整个API生效)
If you want every endpoint in your API to return JSON (no XML responses at all), you can modify the global Web API configuration. Open your WebApiConfig.cs file and update the Register method to remove the XML formatter:
public static void Register(HttpConfiguration config) { // Remove the XML formatter so only JSON is used config.Formatters.Remove(config.Formatters.XmlFormatter); // Optional: Configure JSON formatting preferences (like pretty-printing) config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Optional: Use camelCase for JSON properties }
This way, every response from your API will be JSON, no exceptions.
Pick the approach that fits your needs best—if it's just this one method, go with option 1 or 2. If you want all endpoints to return JSON, option 3 is the way to go.
内容的提问来源于stack exchange,提问作者Karan




