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

在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提交表单即可

原文地址:https://www.cnblogs.com/grj001/p/12224003.html