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


 我有一個支付寶服務網關是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);
        }private HttpResponseMessage GetHttpResponseMessage(string msg)
        {
            return new HttpResponseMessage { Content = new StringContent(msg, Encoding.GetEncoding("UTF-8"), "application/json") };
        }
    }
}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM