
在没有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 ̄)づ╭?~
评价
排名
22
文章
14
粉丝
21
评论
27
腾讯防水墙
赖成龙 :
学长你有下载好的js文件吗
使用 JSON WEB TOKEN (jwt) 验证
饰心 : 由于最近换了新的工作环境,还在挖煤中。后续会增加博客更新频率。
腾讯防水墙
饰心 : @剑轩,快去给tnblog弄一个
使用select2实现下拉框中显示图片
剑轩 : 秀啊.....,飞常不错
使用select2实现下拉框中显示图片
饰心 : 嗯~刚好差不多下班
使用swagger创建webapi文档描述---详解
剑轩 : mark,后面看
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术
风清月
牛掰o( ̄▽ ̄)d ,这种控制台的效果看着就是要比有界面的高端一些
雨雨雨雨辰
66666