webapi

zyip發表於2014-01-27

 

client:

function save()
        {
            var obj = { "name": "zhaoyao", "age": 20, "gender": true, nationality: 'china' };
            //jQuery('#form1').serializeObject().msg
            //JSON.stringify(jQuery('#form1').serializeObject())

            $.ajax({
                type: 'PUT',//POST
                //url: '/api/m',
                url: '/api/m/5',
                data: JSON.stringify(jQuery('#form1').serializeObject()),
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (results) {
                    alert('Customer Added !');
                }
            })

        }

 

 

 

server:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using BLL;

namespace WeChatSchools
{
    public class MController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<Person> Get()
        {
            return new Person[] { new Person() { name = "zhaoyao", age = 20, gender = true }, new Person() { name = "xiaohan", age = 18, gender = false }, new Person { name = "sth", age = 21, gender = true } };
        }

        // GET api/<controller>/5
        public Person Get(int id)
        {
            Person Customer = new Person();
            Customer.name = "Lucy";
            Customer.age = 20;
            Customer.gender = true;


            return Customer;
        }

        // POST api/<controller>
        public void Post([FromBody]Person value)
        {
            int i = 0;
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}

 

BLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class Person
    {
        public string name;
        public int age;
        public bool gender;
    }
}

 

WebApiConfig

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WeChatSchools
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            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);  

        }
    }
}

 

 

 

 http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

 

 

 

 

相關文章