日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > asp.net >内容正文

asp.net

asp.net webapi 自托管插件式服务(转)

發(fā)布時(shí)間:2025/3/15 asp.net 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 asp.net webapi 自托管插件式服务(转) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

  webapi問(wèn)世已久,稀里糊涂的人哪它都當(dāng)mvc來(lái)使,畢竟已mvc使用級(jí)別的經(jīng)驗(yàn)就可以應(yīng)對(duì)webapi。

  webapi和mvc在asp.net5時(shí)代合體了,這告訴我們,其實(shí) 它倆還是有區(qū)別的,要不現(xiàn)在也不會(huì)取兩個(gè)名字,但是由于本人歸納總結(jié)能力較差,各種不同也無(wú)法一一列出了。

?

  在webapi中?HelpPage是個(gè)突出而又實(shí)用的東西,它尼瑪會(huì)把我們code中的注釋生成xml,然后以web頁(yè)面的方式把接口文檔展示出來(lái),這尼瑪無(wú)形就下崗一批文案了,以社會(huì)責(zé)任感角度來(lái)講,ms的這個(gè)HelpPage挺不地道的,但我表示就喜歡這樣的東西。。

  步驟也很簡(jiǎn)單:

    1、negut 搜 helppage ,認(rèn)準(zhǔn)Id是Microsoft.AspNet.WebApi.HelpPage就Install它;

    2、新建一個(gè)xml文件,在項(xiàng)目屬性-生成中 xml文檔文件路徑指向它 勾選;

    3、引入生成的HelpPage中HelpPageConfig.cs中,此代碼“config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/ApiDocument.xml")));”,修改xml路徑 然后解注釋;

    4、最后一生成就會(huì)發(fā)現(xiàn)你寫(xiě)的并沒(méi)有卵用的注釋被一坨一坨塞入了那個(gè)xml文件當(dāng)中,當(dāng)訪(fǎng)問(wèn)help/index 就會(huì)看到配圖如下:

    (附詳細(xì)參考一份:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages)

    

?

    5、Negut認(rèn)準(zhǔn)Id:WebApiTestClient,Install它,你會(huì)發(fā)現(xiàn)多了一個(gè)js、一個(gè)cs、兩個(gè)cshtml文件,都是TestClient開(kāi)頭的,別處用的時(shí)候不要忘了靠它。

      Api.cshtml文件中加入兩行代碼   

1 2 3 4 5 @Html.DisplayForModel("TestClientDialogs") @section Scripts{ ????<link href="~/Areas/HelpPage/TestClient.css"?rel="stylesheet"?/> ????@Html.DisplayForModel("TestClientReferences") }

      點(diǎn)入某一個(gè)接口以后,戳那個(gè)Test Api,你的項(xiàng)目就可以進(jìn)行接口測(cè)試了。此刻你會(huì)更堅(jiān)定自己身為碼農(nóng)的存在,我們并不是coder,我們不生產(chǎn)代碼,我們只是代碼的搬運(yùn)工。

    (附詳細(xì)參考一份:https://blogs.msdn.microsoft.com/yaohuang1/2012/12/02/adding-a-simple-test-client-to-asp-net-web-api-help-page/)

    

?

?

  微幅扯淡之后,言入主題,畢竟文章精髓的要藏在后面。

  從文章標(biāo)題來(lái)看,就可以分成兩個(gè)部分,webapi可以寄宿iis、console、winform、winservice等,插件開(kāi)發(fā)大家也不陌生,所以精髓的部分也言簡(jiǎn)意賅了,這也是很無(wú)奈的事情啊。

  1、使用Self Host自托管方式,negut-Id:Microsoft.AspNet.WebApi.SelfHost

    1.1?首先準(zhǔn)備一個(gè)contrller和model,代碼很簡(jiǎn)單

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public?class?Product ????{ ????????public?int?Id {?get;?set; } ????????public?string?Name {?get;?set; } ????????public?string?Category {?get;?set; } ????????public?decimal?Price {?get;?set; } ????} public?class?ProductsController : ApiController ????{ ????????Product[] products =?new?Product[]? ????????{? ????????????new?Product { Id = 1, Name =?"Tomato Soup", Category =?"Groceries", Price = 1 },? ????????????new?Product { Id = 2, Name =?"Yo-yo", Category =?"Toys", Price = 3.75M },? ????????????new?Product { Id = 3, Name =?"Hammer", Category =?"Hardware", Price = 16.99M }? ????????}; ????????public?IEnumerable<Product> GetAllProducts() ????????{ ????????????return?products; ????????} ????????public?Product GetProductById(int?id) ????????{ ????????????var?product = products.FirstOrDefault((p) => p.Id == id); ????????????if?(product ==?null) ????????????{ ????????????????throw?new?HttpResponseException(HttpStatusCode.NotFound); ????????????} ????????????return?product; ????????} ????????public?IEnumerable<Product> GetProductsByCategory(string?category) ????????{ ????????????return?products.Where(p =>?string.Equals(p.Category, category, ????????????????????StringComparison.OrdinalIgnoreCase)); ????????} ????}

    1.2 寄宿于console,監(jiān)聽(tīng)port,配置route,啟動(dòng)service,一目了然

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class?Program ???{ ???????static?void?Main(string[] args) ???????{ ???????????Console.WriteLine("請(qǐng)輸入監(jiān)聽(tīng)端口"); ???????????string?port = Console.ReadLine(); ???????????var?config =?new?HttpSelfHostConfiguration(string.Format("http://localhost:{0}", port ???"8080")); ???????????config.Routes.MapHttpRoute( ???????????????"API Default",?"api/{controller}/{id}", ???????????????new?{ id = RouteParameter.Optional }); ???????????using?(HttpSelfHostServer server =?new?HttpSelfHostServer(config)) ???????????{ ???????????????server.OpenAsync().Wait(); ???????????????Console.WriteLine("Press ESC to quit."); ???????????????while?( ??????????????!Console.ReadKey().Key.Equals(ConsoleKey.Escape)) ???????????????{ } ???????????} ???????} ???}

    1.3 用winservice來(lái)承載webapi服務(wù)

      首先:?Install-Package Microsoft.AspNet.WebApi.OwinSelfHost? (提到Asp.Net?Owin一句話(huà)可形容,Asp.Net5跨平臺(tái),此逼功不可沒(méi)啊)

      新建好winserver項(xiàng)目后就可以新建一個(gè)Owin的啟動(dòng)類(lèi)別,在其當(dāng)中構(gòu)建webapi的配置

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public?class?Startup ????{ ????????public?void?Configuration(IAppBuilder appBuilder) ????????{ ????????????// Configure Web API for self-host. ????????????HttpConfiguration config =?new?HttpConfiguration(); ????????????config.Routes.MapHttpRoute( ????????????????name:?"DefaultApi", ????????????????routeTemplate:?"api/{controller}/{id}", ????????????????defaults:?new?{ id = RouteParameter.Optional } ????????????); ????????????//config.Services.Replace(typeof(IAssembliesResolver), new PluginsResolver()); ????????????appBuilder.UseWebApi(config); ????????} ????}

      在service中啟動(dòng),over。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 private?IDisposable _apiserver =?null; ????????protected?override?void?OnStart(string[] args) ????????{ ????????????//Services URI ????????????string?serveruri =?string.Format("http://localhost:{0}/", System.Configuration.ConfigurationManager.AppSettings["port"]); ????????????// Start OWIN host? ????????????_apiserver = WebApp.Start<Startup>(url: serveruri); ????????????base.OnStart(args); ????????} ????????protected?override?void?OnStop() ????????{ ????????????if?(_apiserver !=?null) ????????????{ ????????????????_apiserver.Dispose(); ????????????} ????????????base.OnStop(); ????????}

  2、插件式服務(wù),看似逼格很高,其實(shí)只是標(biāo)題黨,畫(huà)龍點(diǎn)睛的代碼到了...

    重寫(xiě)DefaultAssembliesResolver的GetAssemblies,反射加載指定文件下的dll中的controller,在WebApiConifg添加其實(shí)現(xiàn)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public?class?PluginsResolver : DefaultAssembliesResolver ????{ ????????public?override?ICollection<Assembly> GetAssemblies() ????????{ ????????????//動(dòng)態(tài)加載dll中的Controller,類(lèi)似于插件服務(wù),在WebApiConifg中添加配置 ????????????// config.Services.Replace(typeof(IAssembliesResolver), new PluginsResolver()); ????????????List<Assembly> assemblies =?new?List<Assembly>(base.GetAssemblies()); ????????????string?directoryPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory,?"dynamic_services"); ????????????string[] files = Directory.GetFiles(directoryPath); ????????????foreach?(var?fileName?in?files) ????????????{ ????????????????assemblies.Add(Assembly.LoadFrom(Path.Combine(directoryPath, fileName))); ????????????} ????????????return?assemblies; ????????} ????}

    需要什么接口服務(wù)直接寫(xiě)好dll仍進(jìn)dynamic_services文件夾下就有了。

?

原文地址:https://www.cnblogs.com/NotAnEmpty/p/5667582.html

轉(zhuǎn)載于:https://www.cnblogs.com/lenmom/p/8513277.html

總結(jié)

以上是生活随笔為你收集整理的asp.net webapi 自托管插件式服务(转)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。