在GitHub上有個項目,本來是作為自己研究學習.net core的Demo,沒想到很多同學在看,還給了很多星,所以覺得應該升成3.0,整理一下,寫成博分享給學習.net core的同學們。
項目名稱:Asp.NetCoreExperiment
項目地址:https://github.com/axzxs2001/Asp.NetCoreExperiment
當你想用asp.net core做一個三方庫,不但有api實現功能,還希望能用UI來展現或設置你的功能時,這個blog或許對你有用。
用Demo說話,源碼GiuHub庫:https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/EmbeddedResources
創建兩(或三個)個項目
一個是asp.net core web mvc項目(也可打包,發布到nuget上,供他人使用):
1、就是帶UI的庫,因為作為一個庫項目,所以這個項目的Program.cs和Starup.cs就沒有作用了,其實只留 下Controller和Views就好了
2、wwwroot中的前端資源(js,css)還是需要存在的(只保留項目中View用到的前端資源文件就可以),再把view中引用的前端資源的路徑加上wwwroot
3、同時項目“輸出類型”改為“類庫”,接下來,把views中的文件,wwwroot中的文件的屬性從“內容”改成“嵌入的資源”;
4、同時對Controller中的Action使用對應的HttpGet,HttpPost,HttpPut,HttpDelete等請求謂詞和准確的請求url
另一個項目是API或Web MVC項目,只需要Startup.cs中引入
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddControllersWithViews().AddRazorRuntimeCompilation(option => 4 { 5 option.FileProviders.Add(new EmbeddedFileProvider(typeof(EmbeddedResourcesPage.Controllers.PageController).GetTypeInfo().Assembly)); 6 }); 7 } 8 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 9 { 10 app.UseStaticFiles(new StaticFileOptions 11 { 12 FileProvider = new EmbeddedFileProvider(typeof(EmbeddedResourcesPage.Controllers.PageController).GetTypeInfo().Assembly) 13 }); 14 …… 15 }