tnblog
首页
视频
资源
登录

控制台应用程序托管webapi

6041人阅读 2019/3/19 10:58 总访问:115876 评论:2 收藏:0 手机
分类: C#

在没有iis的情况下,webapi是可以自托管的

so,我们从写一个webapi程序开始:

1、创建一个控制台应用程序,然后在控制台应用程序里面"假装”写一个webapi接口:

using EasyTeam.Problem.Web.Api.Models;
using SpeechLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;//此引用需额外引用

namespace EasyTeam.ViocePlay
{
  public class VoicePlayController:ApiController
  {
    /// <summary>
    /// 假装写一个接口
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    [HttpGet]
    public string GetName(string name)
    {
       return "Hello ! "+ name;
    }
  }
}

嗯,现在我们有一个Controller了

二、接着就差个路由了

人家是在Global里面注册路由的啊,咱们这玩意没有Global啊!没关系,咱们有Main函数啊,都是程序入口,也一样对吧?

那就开始:

using EasyTeam.Core.Log;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace EasyTeam.ViocePlay
{
  class Program
  {
     /// <summary>
     /// 控制台应用程序托管webapi
     /// </summary>
     /// <param name="args"></param>
     static void Main(string[] args)
     {
         try
         {
             //注册路由
             var config = new HttpSelfHostConfiguration("http://localhost:8080");//端口,可以把这个端口配置写到配置文件里面

             config.Routes.MapHttpRoute(
                     "API Default",
                     "api/{controller}/{id}",
                     new
                     {
                        id = RouteParameter.Optional
                     });

             using(HttpSelfHostServer server = new HttpSelfHostServer(config))
             {
                server.OpenAsync().Wait();//需以管理员身份运行,否则会报没有访问权限错误!
                Console.WriteLine("Server Listening at 8080...");
                while (true)
                {
                    Console.ReadKey();
                }
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             FileLog.SaveLog(ex, "messageApi.err.log");
             throw;
         }
      }

  }
}


三、接下来就是运行控制台程序了,嗯。。。再测试一下

运行效果:

测试效果:

    ok !so (づ ̄3 ̄)づ╭?~


评价
Decorating heart
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术