Google Code Prettify

[Web API]讓 Web API 預設傳回 JSON 字串

在 \App_Start\WebApiConfig.cs 中加二行程式,加上之後,以後所有回傳的資料就都會是 JSON 字串


using System.Web.Http;
using System.Linq;

namespace TokenTest
{
    public static class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        }
    }
}

之後不必用 string s = JsonConvert.SerializeObject(listUserInfo) ,回傳的範例程式如下:

[HttpGet]
[Route("api/User/GetAllUserInfo")]
public List<UserInfo> GetAllAsync()
{
 List<UserInfo> listUserInfo = new List<UserInfo>();
 var db = new TokenDbContext();
 var usr = db.User.SqlQuery("select * from Users where Name='Morse'");
 foreach(User u in usr) {
  listUserInfo.Add(new UserInfo {
   Id = u.Id.ToString(),
   Name = u.Name,
   Password = u.Password
  });
 }
 return listUserInfo;
}

Rest let  執行結果:


Chrome 執行結果:

Firefox 執行結果: