创建一个简单的API项目(支持跨域)

摘要:
创建三个项目并将其留空。

创建一个简单的API项目(支持跨域)第1张

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

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项目(支持跨域)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇【进制】二进制十进制转换练习HOOK自绘原理下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

Git安装配置(完整版)

/usr/bin/bashcd/var/www/aunsetGIT_DIRgitpulloriginmaster为您提供了另一个权限:chmod755/var/gitdata/a。git/books/post-receivechowngit:git/var/gitdata/a在git/hooks/post-receive模式下,客户端提交代码,服务器项目可以...

爬虫发起抓取被服务器拒绝访问返回403禁止访问解决方案

目前,许多网站的API接口返回的http代码返回代码为403,表示禁止访问。如果您也遇到这种情况,请不要急于首先修改网站的相关参数,即高级api的网站。使用浏览器访问。如果浏览器访问api接口,它可以成功。表示已设置权限。接口可能已被修改或无效,此时无法访问。调用此接口时,将捕获异常中的responseBody。数据很可能在该区域。这就是作者遇到的问题。直接...

Centos7 挂载

1.Mount命令:Mount语法格式:Mount Mount设备文件信息Mount point(目录)注意:装载点(目录)必须有一个装载CD-ROM驱动器:Mount/dev/cdrom/mnt 2.卸载命令:umount语法格式:umountmount point(directory)3.查看磁盘装载状态/查看磁盘使用情况df4。存储设备通电时自动装载#...

学习Python3 天眼查 爬虫

在开始学习Python时,我不想看基础知识,而且我的记忆力很差。我记不住那些语法,所以我直接去了这个项目。这是相当深刻的。刚好公司有情况需要检查企业的信息,所以我想成为一名爬虫。那些有验证码的人不愿意这样做。这是个大问题。我选择了天眼查,跳过检查过程,直接写下结果。总结的步骤如下:首先,天眼查最大的障碍是字体问题。本网站上有介绍,大致意思是网页上显示的一些字...

Cesium深入浅出之视频投影【转】

通常,我们使用矩形,因为视频形状是方形的。据怀疑,视频标签隐藏了这段关系。如果再次显示,视频将再次移动。此处使用VideoSynchronizer。它可以使视频元素与铯的模拟时钟同步。让我们看看它的构造函数:name type description optionsObject option子属性:name type默认值description用于驱动视频的...

【问题】如何批量导出AI文件里内嵌的图片

截止目前为止,新版的AI里面没有直接可以批量导出内嵌图片的选项,手动一个个导出实在太麻烦了。有人说用Phantasm插件可以导出,但新版的找不到对应支持的插件版本,所以这里就不说了。这里介绍一种简单粗暴的方法。...