NET Framework項目移植到NET Core上遇到的一系列坑(2)

来源:https://www.cnblogs.com/team-xiong/archive/2019/12/19/12066242.html
-Advertisement-
Play Games

目錄 獲取請求的參數 獲取完整的請求路徑 獲取功能變數名稱 編碼 文件上傳的保存方法 獲取物理路徑 返回Json屬性大小寫問題 webconfig的配置移植到appsettings.json 設置區域塊MVC的路由器和訪問區域塊的視圖 NetCore訪問靜態資源文件 MVC調用子頁視圖 過濾器 使用sess ...


目錄

  1. 獲取請求的參數
  2. 獲取完整的請求路徑
  3. 獲取功能變數名稱
  4. 編碼
  5. 文件上傳的保存方法
  6. 獲取物理路徑
  7. 返回Json屬性大小寫問題
  8. webconfig的配置移植到appsettings.json
  9. 設置區域塊MVC的路由器和訪問區域塊的視圖
  10. NetCore訪問靜態資源文件
  11. MVC調用子頁視圖
  12. 過濾器
  13. 使用session和解決sessionID一直變化的問題
  14. MD5加密
  15. Path.Combine()
  16. DateTime

1.獲取請求的參數

NET Framework版本:

1 Request["xxx"];
2 Request.Files[0];

NET Core版本:

1 Request.Form["xxx"];
2 Request.Form.Files[0];

2.獲取完整的請求路徑

NET Framework版本:

1 Request.RequestUri.ToString(); 

NET Core版本:

1 //先添加引用
2  
3 using Microsoft.AspNetCore.Http.Extensions;
4  
5 //再調用
6 Request.GetDisplayUrl();

 

3.獲取功能變數名稱

NET Framework版本:

1 HttpContext.Current.Request.Url.Authority

NET Core版本:

1 HttpContext.Request.Host.Value
 

4.編碼

NET Framework版本:

1 System.Web.HttpContext.Current.Server.UrlEncode("<li class=\"test\"></li>")
2 "%3cli+class%3d%22test%22%3e%3c%2fli%3e"
3 System.Web.HttpContext.Current.Server.UrlDecode("%3cli+class%3d%22test%22%3e%3c%2fli%3e")
4 "<li class=\"test\"></li>"

NET Core版本:

 1 //兩種方法,建議用System.Web.HttpUtility
 2 System.Web.HttpUtility.UrlEncode("<li class=\"test\"></li>");
 3 "%3cli+class%3d%22test%22%3e%3c%2fli%3e"
 4 System.Web.HttpUtility.UrlDecode("%3cli+class%3d%22test%22%3e%3c%2fli%3e");
 5 "<li class=\"test\"></li>"
 6  
 7 System.Net.WebUtility.UrlEncode("<li class=\"test\"></li>")
 8 "%3Cli+class%3D%22test%22%3E%3C%2Fli%3E"
 9 System.Net.WebUtility.UrlDecode("%3Cli+class%3D%22test%22%3E%3C%2Fli%3E")
10 "<li class=\"test\"></li>"
11 System.Net.WebUtility.UrlDecode("%3cli+class%3d%22test%22%3e%3c%2fli%3e")
12 "<li class=\"test\"></li>"

 

 

5.文件上傳的保存方法

NET Framework版本:

1 var file = Request.Files[0];
2  
3 //blockFullPath指保存的物理路徑
4  
5 file.SaveAs(blockFullPath);

NET Core版本:

 1 var file = Request.Form.Files[0];
 2  
 3 //blockFullPath指保存的物理路徑
 4  
 5 using (FileStream fs = new FileStream(blockFullPath, FileMode.CreateNew))
 6  
 7 {
 8  
 9 file.CopyTo(fs);
10  
11 fs.Flush();
12  
13 }

 

 

6.獲取物理路徑

NET Framework版本:

1 //作為一個全局變數獲取物理路徑的方法
2  
3 public string ffmpegPathc = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/ffmpeg/ffmpeg.exe");
4  
5 //獲取在控制器的構造函數里直接調用Server.MapPath
6  
7 ffmpegPathc = Server.MapPath("~/Content/ffmpeg/ffmpeg.exe");

NET Core版本:

 1 //從ASP.NET Core RC2開始,可以通過註入 IHostingEnvironment 服務對象來取得Web根目錄和內容根目錄的物理路徑。代碼如下:
 2 
 3  
 4 [Area("Admin")]
 5  
 6 public class FileUploadController : Controller
 7  
 8 {
 9  
10 private readonly IHostingEnvironment _hostingEnvironment;
11  
12  
13  
14 public string ffmpegPathc = "";//System.Web.Hosting.HostingEnvironment.MapPath("~/Content/ffmpeg/ffmpeg.exe");
15  
16  
17  
18 public FileUploadController(IHostingEnvironment hostingEnvironment)
19  
20 {
21  
22 _hostingEnvironment = hostingEnvironment;
23  
24 ffmpegPathc = _hostingEnvironment.WebRootPath + "/Content/ffmpeg/ffmpeg.exe";
25  
26 }
27  
28 }

 

這樣寫每個控制器就都要寫一個構造函數,很麻煩,所以可以把它抽離出來,寫個公共類去調用。代碼如下:

先自定義一個靜態類:

 1 using Microsoft.AspNetCore.Hosting;
 2  
 3 using Microsoft.Extensions.DependencyInjection;
 4  
 5 using System;
 6  
 7  
 8  
 9 namespace GDSMPlateForm
10  
11 {
12  
13 public static class HttpHelper
14  
15 {
16  
17 public static IServiceProvider ServiceProvider { get; set; }
18  
19  
20  
21 public static string GetServerPath(string path)
22  
23 {
24  
25 return ServiceProvider.GetRequiredService<IHostingEnvironment>().WebRootPath + path;
26  
27 }
28  
29 }
30  
31 }

然後 在startup類下的Configure 方法下:

1 HttpHelper.ServiceProvider = app.ApplicationServices;

startup下的ConfigureServices放下註冊方法(這一步必不可少,但是這裡可以不寫,因為IHostingEnvironment 是微軟預設已經幫你註冊了,如果是自己的服務,那麼必須註冊)。

1 services.AddSingleton<IHostingEnvironment, HostingEnvironment>();

最後獲取物理路徑就可以這樣直接調用了:

1 public string ffmpegPathc = HttpHelper.GetServerPath("/Content/ffmpeg/ffmpeg.exe");

 

7.返回Json屬性大小寫問題

NET Core返回Json屬性預設都會自動轉為小寫,但項目之前Json屬性有些是大寫的,所以需要配置成不轉化為小寫的形式。

Startup.cs的ConfigureServices方法下添加一行代碼:

1 //Startup需要添加引用
2  
3 using Newtonsoft.Json.Serialization;
4  
5 //返回Json屬性預設大小寫
6  
7 services.AddMvc().AddJsonOptions(o => { o.SerializerSettings.ContractResolver = new DefaultContractResolver(); });

 

8.webconfig的配置移植到appsettings.json

NET Framework版本:

直接可以讀取webconfig配置文件:

string format = System.Configuration.ConfigurationManager.AppSettings["format"].ToString();

NET Core版本:

NET Core不再支持web.config,取而代之的是appsettings.json,所以需要把一些配置移植過去。

例如web.config下的一些配置

 1 <appSettings>
 2  
 3 <add key="ismdb" value="" />
 4  
 5 <add key="webpath" value="" />
 6  
 7 <add key="format" value="jpg,jpeg,png,gif,bmp,tif,svg/mp3,wav/mp4,avi,mpg,wmv,mkv,rmvb,mov,flv/zip/.ppt,.pptx" />
 8  
 9 <add key="imagesize" value="5242880" />
10  
11 <!--1024 * 1024 * 5 -->
12  
13 <add key="musicsize" value="20971520" />
14  
15 <!--1024 * 1024 * 20 -->
16  
17 <add key="mediasize" value="20971520" />
18  
19 <!--1024 * 1024 * 20 -->
20  
21 <add key="packagesize" value="0" />
22  
23 <add key="pptsize" value="0" />
24  
25 </appSettings>

移植到appsettings.json

 1 {
 2  
 3 "Logging": {
 4  
 5 "IncludeScopes": false,
 6  
 7 "LogLevel": {
 8  
 9 "Default": "Warning"
10  
11 }
12  
13 },
14  
15 "webpath": "",
16  
17 "format": "jpg,jpeg,png,gif,bmp,tif,svg/mp3,wav/mp4,avi,mpg,wmv,mkv,rmvb,mov,flv/zip/.ppt,.pptx",
18  
19 "imagesize": "5242880",
20  
21 "musicsize": "20971520",
22  
23 "mediasize": "20971520",
24  
25 "packagesize": "0",
26  
27 "pptsize": "0"
28  
29 }

然後編寫一個類去調用這個appsettings.json

 1 using Microsoft.Extensions.Configuration;
 2  
 3 using System.IO;
 4  
 5  
 6  
 7 namespace GDSMPlateForm
 8  
 9 {
10  
11 public class RConfigureManage
12  
13 {
14  
15 public static string GetConfigure(string key)
16  
17 {
18  
19  
20  
21 //添加 json 文件路徑
22  
23 var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
24  
25 //創建配置根對象
26  
27 var configurationRoot = builder.Build();
28  
29  
30  
31 //取配置根下的 name 部分
32  
33 string secvalue = configurationRoot.GetSection(key).Value;
34  
35 return secvalue;
36  
37 }
38  
39 }
40  
41 }

調用的方式:

1 string format = RConfigureManage.GetConfigure("format");

 

9.設置區域塊MVC的路由器和訪問區域塊的視圖

NET Framework版本:

NET Framework新建一個區域會自帶一個類設置路由器的,如圖:

 

 
 1 using System.Web.Mvc;
 2  
 3  
 4  
 5 namespace GDSMPlateForm.Areas.Admin
 6  
 7 {
 8  
 9 public class AdminAreaRegistration : AreaRegistration
10  
11 {
12  
13 public override string AreaName
14  
15 {
16  
17 get
18  
19 {
20  
21 return "Admin";
22  
23 }
24  
25 }
26  
27  
28  
29 public override void RegisterArea(AreaRegistrationContext context)
30  
31 {
32  
33 context.MapRoute(
34  
35 "Admin_default",
36  
37 "Admin/{controller}/{action}/{id}",
38  
39 new { action = "Index", id = UrlParameter.Optional }
40  
41 );
42  
43 }
44  
45 }
46  
47 }

NET Core版本:

NET Core新建一個區域不會自帶一個類用於設置路由器,所以需要在Startup類的Configure方法里多加一條路由器設置

 1 app.UseMvc(routes =>
 2  
 3 {
 4  
 5 routes.MapRoute(
 6  
 7 name: "areas",
 8  
 9 template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
10  
11 );
12  
13 });

 

然後需要在每個控制器下添加一個標簽,指定該控制器屬於哪個區域的,如圖:

不加的話訪問不到區域的視圖,報404錯誤。

 

10.NetCore訪問靜態資源文件

NET Framework版本:

NET Framework可以在webconfig下配置這些靜態資源文件

1 <staticContent>
2  
3 <mimeMap fileExtension="." mimeType="image/svg+xml" />
4  
5 <mimeMap fileExtension=".properties" mimeType="application/octet-stream" />
6  
7 </staticContent>

NET Core版本:

NET Core並沒有webconfig,所以需要在Startup類的Configure方法里自己配置。

NET Core項目預設的資源文件存在wwwroot下,可以通過app.UseStaticFiles方法自己定義資源文件的路徑還有類型。

 1 ar provider = new FileExtensionContentTypeProvider();
 2  
 3 provider.Mappings[".properties"] = "application/octet-stream";
 4  
 5 app.UseStaticFiles(new StaticFileOptions
 6  
 7 {
 8  
 9 FileProvider = new PhysicalFileProvider(
10  
11 Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Content")),
12  
13 RequestPath = "/Content",
14  
15 ContentTypeProvider = provider
16  
17 });

 

11.MVC調用子頁視圖

NET Framework版本:

1 @Html.Action("UserBackView", "UserManage")

NET Core版本:

NET Core不再支持Html.Action(),不過可以手動自己去實現它。

自定義一個靜態類 HtmlHelperViewExtensions,命名空間設置為  Microsoft.AspNetCore.Mvc.Rendering。網上找的一個類,複製過來就行了,如下:

  1 using Microsoft.AspNetCore.Html;
  2  
  3 using Microsoft.AspNetCore.Http;
  4  
  5 using Microsoft.AspNetCore.Mvc.Infrastructure;
  6  
  7 using Microsoft.AspNetCore.Routing;
  8  
  9 using Microsoft.Extensions.DependencyInjection;
 10  
 11 using System;
 12  
 13 using System.IO;
 14  
 15 using System.Threading.Tasks;
 16  
 17  
 18  
 19 namespace Microsoft.AspNetCore.Mvc.Rendering
 20  
 21 {
 22  
 23 public static class HtmlHelperViewExtensions
 24  
 25 {
 26  
 27 public static IHtmlContent Action(this IHtmlHelper helper, string action, object parameters = null)
 28  
 29 {
 30  
 31 var controller = (string)helper.ViewContext.RouteData.Values["controller"];
 32  
 33  
 34  
 35 return Action(helper, action, controller, parameters);
 36  
 37 }
 38  
 39  
 40  
 41 public static IHtmlContent Action(this IHtmlHelper helper, string action, string controller, object parameters = null)
 42  
 43 {
 44  
 45 var area = (string)helper.ViewContext.RouteData.Values["area"];
 46  
 47  
 48  
 49 return Action(helper, action, controller, area, parameters);
 50  
 51 }
 52  
 53  
 54  
 55 public static IHtmlContent Action(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)
 56  
 57 {
 58  
 59 if (action == null)
 60  
 61 throw new ArgumentNullException("action");
 62  
 63  
 64  
 65 if (controller == null)
 66  
 67 throw new ArgumentNullException("controller");
 68  
 69  
 70  
 71  
 72  
 73 var task = RenderActionAsync(helper, action, controller, area, parameters);
 74  
 75  
 76  
 77 return task.Result;
 78  
 79 }
 80  
 81  
 82  
 83 private static async Task<IHtmlContent> RenderActionAsync(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)
 84  
 85 {
 86  
 87 // fetching required services for invocation
 88  
 89 var serviceProvider = helper.ViewContext.HttpContext.RequestServices;
 90  
 91 var actionContextAccessor = helper.ViewContext.HttpContext.RequestServices.GetRequiredService<IActionContextAccessor>();
 92  
 93 var httpContextAccessor = helper.ViewContext.HttpContext.RequestServices.GetRequiredService<IHttpContextAccessor>();
 94  
 95 var actionSelector = serviceProvider.GetRequiredService<IActionSelector>();
 96  
 97  
 98  
 99 // creating new action invocation context
100  
101 var routeData = new RouteData();
102  
103 foreach (var router in helper.ViewContext.RouteData.Routers)
104  
105 {
106  
107 routeData.PushState(router, null, null);
108  
109 }
110  
111 routeData.PushState(null, new RouteValueDictionary(new { controller = controller, action = action, area = area }), null);
112  
113 routeData.PushState(null, new RouteValueDictionary(parameters ?? new { }), null);
114  
115  
116  
117 //get the actiondescriptor
118  
119 RouteContext routeContext = new RouteContext(helper.ViewContext.HttpContext) { RouteData = routeData };
120  
121 var candidates = actionSelector.SelectCandidates(routeContext);
122  
123 var actionDescriptor = actionSelector.SelectBestCandidate(routeContext, candidates);
124  
125  
126  
127 var originalActionContext = actionContextAccessor.ActionContext;
128  
129 var originalhttpContext = httpContextAccessor.HttpContext;
130  
131 try
132  
133 {
134  
135 var newHttpContext = serviceProvider.GetRequiredService<IHttpContextFactory>().Create(helper.ViewContext.HttpContext.Features);
136  
137 if (newHttpContext.Items.ContainsKey(typeof(IUrlHelper)))
138  
139 {
140  
141 newHttpContext.Items.Remove(typeof(IUrlHelper));
142  
143 }
144  
145 newHttpContext.Response.Body = new MemoryStream();
146  
147 var actionContext = new ActionContext(newHttpContext, routeData, actionDescriptor);
148  
149 actionContextAccessor.ActionContext = actionContext;
150  
151 var invoker = serviceProvider.GetRequiredService<IActionInvokerFactory>().CreateInvoker(actionContext);
152  
153 await invoker.InvokeAsync();
154  
155 newHttpContext.Response.Body.Position = 0;
156  
157 using (var reader = new StreamReader(newHttpContext.Response.Body))
158  
159 {
160  
161 return new HtmlString(reader.ReadToEnd());
162  
163 }
164  
165 }
166  
167 catch (Exception ex)
168  
169 {
170  
171 return new HtmlString(ex.Message);
172  
173 }
174  
175 finally
176  
177 {
178  
179 actionContextAccessor.ActionContext = originalActionContext;
180  
181 httpContextAccessor.HttpContext = originalhttpContext;
182  
183 if (helper.ViewContext.HttpContext.Items.ContainsKey(typeof(IUrlHelper)))
184  
185 {
186  
187 helper.ViewContext.HttpContext.Items.Remove(typeof(IUrlHelper));
188  
189 }
190  
191 }
192  
193 }


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 時間如流水,只能流去不流回! 點贊再看,養成習慣,這是您給我創作的動力! 本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分 ...
  • 首先在ConfigureServices添加 public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("any", builder => ...
  • .NET Core 3.1 作為LTS長期支持版本,會提供3年的支持(明年就出.net5),值得升級(嗎)。 目前主流的第三方包大多都已經提供了支持,2.x => 3.1還是變化不是特別多,EF Core坑就大咯,謹慎。 ASP.NET Core 3.1 的新增功能 https://docs.mic ...
  • 我們搜索一下yum庫關於nginx的rpm包:yum list | grep nginx 找到rpm安裝包,我們就可以使用yum直接安裝了:yum install nginx 修改nginx配置文件:vi /etc/nginx/nginx.conf 註釋掉下麵的配置: 創建一個netcore.con ...
  • WPF中一些圖片處理方案整理,可以大致實現類似PS的一些基本功能:移動,裁剪,摳圖,背景橡皮擦等等 ...
  • Protected 在基類中定義後,能被派生類調用,但是不能被其他類調用。 virtual 在基類中定義後,在派生類中能被重寫。 using System; using System.Collections.Generic; using System.Text; namespace 繼承 { cla ...
  • 一丶簡單介紹下目錄結構和項目依賴,如圖 二丶主要核心自定義代碼 1. 添加自定義實現類 CustomProvider 2. 在silo中註入代替預設實現 3. 在grain類上啟用 三丶運行結果如下 示例代碼下載地址:SimpleStorage ...
  • string strguid = Guid.NewGuid().ToString();//57d99d89-caab-482a-a0e9-a0a803eed3ba 生成標準的標誌符 (36位標準)strguid = Guid.NewGuid().ToString("D");//57d99d89-ca ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...