第一步,使用vs2019新建mvc-web api应用程序
创建bridgeapi
第二步,运行将生成默认的示例网页,网页url为
https://localhost:44361/home/index
右键 项目 添加 webapi控制器类
添加
我们可以看到app_start目录下 有三个文件:
bundleconfig.cs代表 捆绑文件的引用
有脚本文件scriptbundle的引用(javascript文件,后缀名.js)
和层叠样式表文件stylebundle(即css网页排版文件,后缀名.css)
filterconfig.cs代表全局筛选器
routeconfig.cs代表url路由模式和action信息
右键,项目,将类库项目更新为控制台应用程序,并添加类program
添加开源框架topshelf的引用,添加owin框架的引用
topshelf 框架
topshelf 是一个开源的跨平台的宿主服务框架,支持 windows 和 mono,只需要几行代码就可以构建一个很方便使用的服务宿主。
使用 topshelf 可以非常方便的将一个 c# 控制台程序部署成为一个 windows service, 使用它可以很方便的构建跨平台服务寄主,而在调试时直接以控制台的形式运行即可,非常方便。
owin框架
owin 允许 web 应用从 web 服务器分离。 它定义了在管道中使用中间件来处理请求和相关响应的标准方法。 webapi应用程序和中间件可以与基于 owin 的应用程序、服务器和中间件进行互操作。
我们在web.config(有些是app.config)增加webapi地址和端口
apiaddress和apiport
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 asp.net 应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?linkid=301880 --> <configuration> <appsettings> <add key="webpages:version" value="3.0.0.0" /> <add key="webpages:enabled" value="false" /> <add key="clientvalidationenabled" value="true" /> <add key="unobtrusivejavascriptenabled" value="true" /> <add key="apiaddress" value="" /> <add key="apiport" value="45678" /> </appsettings> </configuration>
program.cs如下:
using microsoft.owin.hosting; using owin; using system; using system.collections.generic; using system.configuration; using system.linq; using system.net; using system.threading; using system.threading.tasks; using system.web; using system.web.http; using topshelf; using topshelf.hostconfigurators; /* * topshelf 是一个开源的跨平台的宿主服务框架,支持 windows 和 mono,只需要几行代码就可以构建一个很方便使用的服务宿主。 * 使用 topshelf 可以非常方便的将一个 c# 控制台程序部署成为一个 windows service, 使用它可以很方便的构建跨平台服务寄主, * 而在调试时直接以控制台的形式运行即可,非常方便。 * owin框架 * owin 允许 web 应用从 web 服务器分离。 它定义了在管道中使用中间件来处理请求和相关响应的标准方法。 * webapi应用程序和中间件可以与基于 owin 的应用程序、服务器和中间件进行互操作。 */ namespace bridgeapi { public class program { static void main(string[] args) { console.writeline("webapi程序启动开始..."); hostfactory.run(new action<hostconfigurator>(hostconf)); console.readline(); } public static void hostconf(hostconfigurator hostconfigurator) { // 服务使用network_service内置帐户运行。身份标识,有好几种方式,如:x.runas("username", "password"); x.runasprompt(); x.runasnetworkservice(); 等 hostconfigurator.runaslocalservice();//以服务 //x.startautomatically();//startmodeextensions //x.startmanually();//手动模式 hostconfigurator.setdescription("webapiserver 斯内科 topshelf host服务的描述"); //安装服务后,服务的描述 hostconfigurator.setdisplayname("webapiserversnake"); //显示名称 hostconfigurator.setservicename("webapiserversnake"); //服务名称 type t = hostconfigurator.gettype();//topshelf.hostconfigurators.hostconfiguratorimpl console.writeline(t.tostring()); hostconfigurator.service<towncrier>(s => { s.constructusing(name => new towncrier()); //配置一个完全定制的服务,对topshelf没有依赖关系。常用的方式。 //the start and stop methods for the service s.whenstarted(tc => tc.start()); //4 s.whenstopped(tc => tc.stop()); }); } } public class towncrier { public towncrier() { } public void start() { task.factory.startnew(() => { bool isstarted = false; while (!isstarted) { try { string log = "服务启动成功。"; string urlkey = "apiaddress"; string portkey = "apiport"; if (!configurationmanager.appsettings.allkeys.contains(urlkey)) { log = $"服务启动出现异常:app.config文件中不存在配置[{urlkey}]"; console.writeline(log); return; } if (!configurationmanager.appsettings.allkeys.contains(portkey)) { log = $"服务启动出现异常:app.config文件中不存在配置[{portkey}]"; console.writeline(log); return; } string apiurl = configurationmanager.appsettings[urlkey].tostring(); string apiport = configurationmanager.appsettings[portkey].tostring(); bool rtn = int.tryparse(apiport, out int port); if (!rtn) { log = $"服务启动出现异常:app.config文件中配置[{portkey}]值错误"; console.writeline(log); return; } startoptions options = new startoptions(); //options.urls.add($"http://localhost:{apiport}"); options.urls.add($"http://127.0.0.1:{apiport}"); //options.urls.add($"http://{environment.machinename}:{apiport}"); if (!string.isnullorempty(apiurl)) { options.urls.add($"http://{apiurl}:{apiport}"); } else { #region //自动绑定所有ip string hostname = dns.gethostname(); ipaddress[] ipaddresses = dns.gethostaddresses(hostname); foreach (ipaddress ipaddress in ipaddresses) { //ipv4 if (ipaddress.addressfamily == system.net.sockets.addressfamily.internetwork) { options.urls.add($"http://{ipaddress}:{apiport}"); } } #endregion } string urls = new system.web.script.serialization.javascriptserializer().serialize(options.urls); log = $"开始启动服务,服务地址:{urls}"; console.writeline(log); //owin 托管服务器问题:startoptions webapp.start targetinvocationexception // start owin host ,启动一个webapi程序 // public static idisposable start(string url, action<iappbuilder> startup); webapp.start(options, startup: configuration); console.writeline($"服务启动成功。"); isstarted = true; } catch (exception ex) { console.writeline($"服务启动出现异常:{ex.message}"); thread.sleep(2000); } } }); } public void stop() { console.writeline($"webapi服务退出"); } public void configuration(iappbuilder appbuilder) { // configure web api for self-host. httpconfiguration config = new httpconfiguration(); config.maphttpattributeroutes(); config.routes.maphttproute( name: "defaultapi", routetemplate: "{controller}/{action}/{id}", defaults: new { id = routeparameter.optional } ); appbuilder.usewebapi(config); } } }
控制器类bridgecontroller如下:
using system; using system.collections.generic; using system.linq; using system.net; using system.net.http; using system.web.http; namespace bridgeapi { [routeprefix("bridge")] public class bridgecontroller : apicontroller { /// <summary> /// 测试api端口,假设传入一个json字符串{"testname":"斯内科"} /// 请求路由url不区分大小写 /// http://127.0.0.1:45678/bridge/testapi /// </summary> /// <param name="json"></param> /// <returns></returns> [route("testapi")] [httppost] public httpresponsemessage testapi(object objtext) { try { microsoft.owin.owincontext context = ((microsoft.owin.owincontext)request.properties["ms_owincontext"]); string remoteclient = context.request.remoteipaddress + ":" + context.request.remoteport; if (objtext == null) { string returndatang = newtonsoft.json.jsonconvert.serializeobject(new responsecontent() { code = 12345, message = $"解析失败,请求参数为空,源文本【{objtext}】" }); return new httpresponsemessage() { content = new stringcontent(returndatang, system.text.encoding.utf8, mediatype: "application/json") }; } string json = objtext.tostring(); testclass testclass = newtonsoft.json.jsonconvert.deserializeobject<testclass>(json); if (testclass == null || string.isnullorempty(testclass.testname)) { string returndatang = newtonsoft.json.jsonconvert.serializeobject(new responsecontent() { code = 12345, message = $"解析失败,testname为空,源json【{json}】" }); return new httpresponsemessage() { content = new stringcontent(returndatang, system.text.encoding.utf8, mediatype: "application/json") }; } string returndata = newtonsoft.json.jsonconvert.serializeobject(new responsecontent() { code = 0, message = "", data = $"接收到【{remoteclient}】上抛数据【{json}】,已处理ok,返回一个随机数【{new random().next(1, 100)}】" }); return new httpresponsemessage() { content = new stringcontent(returndata, system.text.encoding.utf8, mediatype: "application/json") }; } catch (exception ex) { string returndatang = newtonsoft.json.jsonconvert.serializeobject(new responsecontent() { code = -1, message = $"处理时出现错误【{ex.message}】" }); return new httpresponsemessage() { content = new stringcontent(returndatang, system.text.encoding.utf8, mediatype: "application/json"), statuscode = httpstatuscode.badrequest }; } } } public class testclass { public string testname { get; set; } } /// <summary> /// 接口反馈的响应内容对象 /// </summary> public class responsecontent { /// <summary> /// 错误号,code为0代表ok /// </summary> public int code { get; set; } /// <summary> /// 错误描述,code为0,这里显示空 /// </summary> public string message { get; set; } /// <summary> /// 相关数据信息,该data可以是数组、键值对字典、字符串等任意类型数据 /// </summary> public object data { get; set; } } }
运行,将其按照服务进行
使用postman测试webapi 接口,如下
以上就是c#使用mvc框架创建webapi服务接口的流程步骤的详细内容,更多关于c# mvc创建webapi接口的资料请关注代码网其它相关文章!
发表评论