2017年7月21日 星期五

[MVC] API to Return XML


  • Solution 
    • If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.
  • Code
    /// 
    /// Demo API
    /// 
    public class DemoController : ApiController
    {
        public class User
        {
            /// 
            /// User Name
            /// 
            public string Name { get; set; }
            /// 
            /// User age
            /// 
            public int Age { get; set; }
        }

        /// 
        /// Get User list
        /// 
        ///  User list 
        public List< User> Post()
        {
            // Get user list
            List< User> lUser = new List< User>()
            {
                new User(){ Name = "Lyndon", Age = 30 },
                new User(){ Name = "Daisy", Age = 27 },
            };

            return lUser;
        }
    }
  • JSON
    • Harders 不需加入任何參數
  • XML
    • Harders 加入 Accept: application/xml
  • Ref:
    • https://stackoverflow.com/questions/11662028/webapi-to-return-xml

沒有留言:

張貼留言