创建一个简单的API项目

创建一个简单的API项目

 

 

 

创建三个项目,空项目即可。

 

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

namespace BFKR.Date
{
    public class Contact
    {
        /// <summary>
        /// ID
        /// </summary>
        public string ID { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 联系电话
        /// </summary>
        public string PhoneNo { get; set; }
        /// <summary>
        /// 电子邮箱
        /// </summary>
        public string EmailAddress { get; set; }
        /// <summary>
        /// 联系地址
        /// </summary>
        public string Address { get; set; }
        /// <summary>
        /// 资料
        /// </summary>
        public List<Information> lisInfo { get; set; }
    }

    public class Information
    {
        public string Education { get; set; }
    }
}

 

配置webapi路由、跨域支持

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

namespace BFKR.API
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //跨域配置
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            //webApi路由
            config.MapHttpAttributeRoutes();

            //设置webapi路由规则
            //config.Routes.MapHttpRoute(
            //    name: "AreaApi",
            //    routeTemplate: "api/{area}/{controller}/{action}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
            //config.Routes.MapHttpRoute(
            //    name: "WebApi",
            //    routeTemplate: "api/{controller}/{action}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);


            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );


            //移除xml返回格式数据
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            //配置返回的时间类型数据格式  
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
                new Newtonsoft.Json.Converters.IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                }
            );
        }
    }
}

 

配置Global

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;

namespace BFKR.API
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

 

编写API

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

namespace BFKR.API.Controller
{
    public class ContactsController : ApiController
    {
        static List<Contact> contacts;

        static ContactsController()
        {
            contacts = new List<Contact>() {
                new Contact { ID = "001", Name = "张三", PhoneNo = "15811100056", EmailAddress = "zhangsanemail@163.com", Address = "北京市", lisInfo = new List<Information>() { new Information { Education = "小学" }, new Information { Education = "中学" } } },
                new Contact { ID = "002", Name = "李四", PhoneNo = "0474-577466", EmailAddress = "lisiemail@163.com", Address = "内蒙古", lisInfo = new List<Information>() { new Information { Education = "高中" }, new Information { Education = "大学" } } }
            };
        }

        public IEnumerable<Contact> Get(string id = null)
        {
            return from contact in contacts
                   where contact.ID == id || string.IsNullOrEmpty(id)
                   select contact;
        }

        public void Post(Contact contact)
        {
            contact.ID = "003";
            contacts.Add(contact);
        }


        public void Put(Contact contact)
        {
            contacts.Remove(contacts.First(C => C.ID == contact.ID));
            contacts.Add(contact);
        }


        public void Delete(string id)
        {
            contacts.Remove(contacts.First(C => C.ID == id));
        }
    }
}

 

 

前段ajax 调用API

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="../Contents/scripts/jquery/jquery-2.1.1.min.js"></script>
</head>
<body>

</body>
</html>

<script type="text/javascript">

    $(function () {
        alert(111);

        $.ajax({
            url: "https://localhost:44314/api/Contacts",
            type: "GET",
            success: function (data) {
                alert(data);
            }
        });

    });


</script>

 

创建一个简单的API项目

上一篇:Kafka Broker源码解析二:API层设计


下一篇:C#反射复习