zoukankan      html  css  js  c++  java
  • 在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提交表单即可

  • 相关阅读:
    mysql在windows下备份&恢复数据库语句
    Postman(三)、获取响应数据
    LoadRunner(八)、常用的接口压测格式
    LoadRunner(七)、集合点
    LoadRunner(六)、事务
    LoadRunner(五)、参数化之文本参数化
    repmgr安装使用
    PostgreSQL 游标的种类
    win server 2019 资源管理器 内存占用高
    给MySQL中某表增加一个新字段,并设为主键值为自动增长。
  • 原文地址:https://www.cnblogs.com/grj001/p/12224002.html
Copyright © 2011-2022 走看看