ASP.NET WebForm中使用WebApi

本文介绍如何在WebForm项目中集成WebApi,包括添加webapi.dll,配置路由及创建ContactsApi类。ContactsApi类提供了获取联系人的方法,并通过http://localhost:9000/API访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加webapi.dll 可现在添加。

在WebForm使用WebApi需要在全局文件里配置路由。

        using System.Web.Routing;

        protected void Application_Start(object sender, EventArgs e)
        {

            RegisterRoutes(RouteTable.Routes);
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            //ContactsApi为暴露的类里面为暴露的方法  API要映射的路径
            routes.MapServiceRoute<ContactsApi>("API");


        }
ContactsApi类的定义
using System.ServiceModel;
using System.ServiceModel.Web;
using WebAPI.Resources;

namespace WebAPI.APIs
{
    [ServiceContract]
    public class ContactsApi
    {

        //设置为默认方法
        [WebGet(UriTemplate = "")]
        public IQueryable<Contact> Get()
        {
            var contacts = new List<Contact>()
                            {
                            new Contact {ContactId =1, Name ="1111"},
                            new Contact {ContactId =2, Name ="333"},
                            new Contact {ContactId =3, Name ="Glenn Block"},
                            new Contact {ContactId =4, Name ="Howard Dierking"},
                            new Contact {ContactId =5, Name ="Jeff Handley"},
                            new Contact {ContactId =6, Name ="Yavor Georgiev"}
                            };
            return contacts.AsQueryable();
        }

    }
}

访问地址为:http://localhost:9000/API

转载于:https://www.cnblogs.com/gouyanfeng/p/3173508.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值