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="[email protected]"}, new Contact{ Id="002",FirstName = "Si", LastName="Li", PhoneNo="456", EmailAddress="[email protected]"} }; 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); }
时间: 2024-10-14 05:49:26