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

  • 相关阅读:
    ORACLE 查看进程数,已执行任务数, 剩余任务数,删除指定任务
    ORACLE 收集统计整个用户数据
    解决Hystrix dashboard Turbine 一直 Loading…… 及其他坑
    利用 Maven 构造 Spring Cloud 微服务架构 模块使用 spring Boot构建
    AES加解密
    JAVA POI XSSFWorkbook导出扩展名为xlsx的Excel,附带weblogic 项目导出Excel文件错误的解决方案
    JAVA 文件的上传下载
    shell启停服务脚本模板
    JAVA 设计模式之 原型模式详解
    JAVA 设计模式之 工厂模式详解
  • 原文地址:https://www.cnblogs.com/pudefu/p/10502244.html
Copyright © 2011-2022 走看看