码迷,mamicode.com
首页 > Windows程序 > 详细

演示如何在 WebForm 中提供 web api 服务

时间:2015-12-24 00:37:35      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

Global.asax.cs

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

namespace WebApiWebFormHost
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            // 配置路由
            RouteTable.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

HelloController.cs

/*
 * 宿主到 iis,通过 WebForm 提供 web api 服务
 * 
 * 测试地址:http://localhost:4723/api/hello
 */

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

namespace WebApiWebFormHost
{
    public class HelloController : ApiController
    {
        public IEnumerable<string> Get()
        {
            string[] names = { "webabcd", "webabcd2", "webabcd3" };
            return names;
        }
    }
}

另一例子

 public class Contact
    {
        public string Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string PhoneNo { get; set; }

        public string EmailAddress { get; set; }
    }
    public class ContactController : ApiController

   {

       private static List<Contact> contacts = new List<Contact>

       {

           new Contact{ Id="001", FirstName = "San", LastName="Zhang", PhoneNo="123", EmailAddress="zhangsan@gmail.com"},

           new Contact{ Id="002",FirstName = "Si", LastName="Li", PhoneNo="456", EmailAddress="lisi@gmail.com"}

       };

           

       public IEnumerable<Contact> Get()

       {

           return contacts;

       }

    

       public Contact Get(string id)

       {

           return contacts.FirstOrDefault(c => c.Id == id);

       }

    

       public void Put(Contact contact)

       {

           if (string.IsNullOrEmpty(contact.Id))

           {

               contact.Id = Guid.NewGuid().ToString();

           }

           contacts.Add(contact);

       }

    

       public void Post(Contact contact)

       {

           Delete(contact.Id);

           contacts.Add(contact);

       }

    

       public void Delete(string id)

       {

           Contact contact = contacts.FirstOrDefault(c => c.Id == id);

           contacts.Remove(contact);

       }

 

演示如何在 WebForm 中提供 web api 服务

标签:

原文地址:http://www.cnblogs.com/longyi/p/5071680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!