1. 程式人生 > >在asp.net web form項目中添加webapi接口

在asp.net web form項目中添加webapi接口

pro ext tap ring pla fix local nta pms

 我有一個支付寶服務網關是ASP.NET WEB FORM項目,但是最近這個網關需要對外提供幾個接口,想了下,使用web api比較合適,實現很簡單,GO

 1,首先添加一個文件夾名字叫App_Start,貌似需要固定名稱

 技術分享圖片

 2.在App_Start文件夾下添加WebApiConfig類,WebApiConfig類代碼如下:

  

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

namespace
AlipayGateway.App_Start { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate:
"api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }

  3.在Global.asax文件的Application_Start函數中添加代碼註冊API路由規則

namespace AlipayGateway
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object
sender, EventArgs e) { GlobalConfiguration.Configure(WebApiConfig.Register); } } }

 4.添加一個控制器

 技術分享圖片

控制器代碼如下:

using AliPayService;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;

namespace AlipayGateway.Controllers
{
    [RoutePrefix("api/sapi")]
    public class SapiController : ApiController
    {
        /// <summary>
        /// 發送支付寶模板消息
        /// </summary>
        /// <returns></returns>

        [Route("sendtempmsg")]
        public HttpResponseMessage SendMsg()
        {
            string pay_type = HttpContext.Current.Request.Form["pay_type"];
            string msg_content = HttpContext.Current.Request.Form["msg_content"];
            string msg = MessageSendBiz.SendTemplateMsg(int.Parse(pay_type), msg_content);
            return GetHttpResponseMessage(msg);
        }
    }
}

調用時向http://localhost:57841/api/sapi/sendtempmsg提交表單即可

在asp.net web form項目中添加webapi接口