Skip to main content
 首页 » 编程设计

c#之MVC .NET Core Web API XML 或 JSON

2024年01月21日24zdz8207

我想创建一个以 XML 或 JSON 格式返回数据的 Web 应用程序,我该怎么做?

模型:

namespace ReturningJSONandXML.Models 
{ 
    public class SomeImportantInformation 
    { 
        public int ID { get; set; } 
        public string Information { get; set; } 
    } 
} 

Controller :

namespace ReturningJSONandXML.Controllers 
{ 
    public class GetInfoController : Controller 
    { 
        // GET: /<controller>/ 
        public List<SomeImportantInformation> Get() 
        { 
            List<SomeImportantInformation> ImportantInfo = new List<SomeImportantInformation>(); 
            ImportantInfo.Add(new SomeImportantInformation { ID = 0, Information = "Awesome info" }); 
            ImportantInfo.Add(new SomeImportantInformation { ID = 1, Information = "Some other interesting info" }); 
            return ImportantInfo; 
        } 
    } 
} 

我想返回一个 XML 和 JSON 文件...

我应该在这里使用哪些最佳实践?

请您参考如下方法:

框架会自动为您处理这件事,这样您就不必重新发明轮子。答案引用如下。

但为简化起见:除非您指定 Accept header ,否则 API 会将响应序列化为 JSON。例如,如果您指定 'application/xml',它将返回 XML。

正如 MSDN 所说:

Content negotiation (conneg for short) occurs when the client specifies an Accept header. The default format used by ASP.NET Core MVC is JSON. Content negotiation is implemented by ObjectResult. It's also built into the status code specific action results returned from the helper methods (which are all based on ObjectResult). You can also return a model type (a class you've defined as your data transfer type) and the framework will automatically wrap it in an ObjectResult for you.

...

Content negotiation only takes place if an Accept header appears in the request. When a request contains an accept header, the framework will enumerate the media types in the accept header in preference order and will try to find a formatter that can produce a response in one of the formats specified by the accept header. In case no formatter is found that can satisfy the client's request, the framework will try to find the first formatter that can produce a response (unless the developer has configured the option on MvcOptions to return 406 Not Acceptable instead). If the request specifies XML, but the XML formatter has not been configured, then the JSON formatter will be used. More generally, if no formatter is configured that can provide the requested format, then the first formatter that can format the object is used. If no header is given, the first formatter that can handle the object to be returned will be used to serialize the response. In this case, there isn't any negotiation taking place - the server is determining what format it will use.

来自 MSDN -- Current version和 version at time of quote .