ASP.NET MVC 4 Web API – Restful Web Services ( JSON ) : POST 方法

ASP.NET MVC 4 Web API – Restful Web Services ( JSON ) : POST 方法

   \App_Start\WebApiConfig.cs
 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Web.Http;
 
   namespace CRMPortal
   {
      public static class WebApiConfig
      {
         public static void Register(HttpConfiguration config)
         {
            … …
 
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );
         }
      }
   }
 
   \Views\Home\Form.cshtml
 
   … …
 
   @using(Html.BeginRouteForm("DefaultApi", new { controller="Rest", httproute="true" })){
      <input type="submit" value="Download" />
   }
 
   … …
 
   \Controllers\RestController.cs
 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Net;
   using System.Net.Http;
   using System.Web.Http;
 
   namespace CRMPortal.Controllers
   {
      public class RestController : ApiController
      {
 
         … …
 
         // POST api/<controller>
         public List<product> Post([FromBody]string value)
         {
            List<product> list = new List<product>();
            product item;
 
            for (int i = 1; i < 100; i++)
            {
 
               item = new product();
               item.id = i;
               item.cat = "Cat " + i;
               item.subcat = "Subcat " + i;
               item.model = "Model " + i;
               item.price = i * 100;
 
               list.Add(item);
 
            }
 
            return list;
         }
 
         … …
 
      }
 
      public class product
      {
         public int id { get; set; }
         public string cat { get; set; }
         public string subcat { get; set; }
         public string model { get; set; }
         public Nullable<long> price { get; set; }
      }
 
   }