Asp.net MVC升级到.Net Core的那些坑

内容纲要

ASP.NET Core是微软新推出的支持跨平台、高性能、开源的开发框架,它的优势不必多说,因为已经说得太多了。当然,现在依然有着数量庞大的系统运行于.NET Framework上,由于有大量的Break Changes,很多项目项目团队也不敢贸然升级,其中的考量也不全部是技术原因,更多的可能还是业务推进因素。

笔者自年前开始考虑升级一套电商系统,原先是基于.NET Framework 4.5的,打算直接升级到.NET Core 3.1,由于系统规模比较庞大,所以一旦开工就是一个漫长的工程,我的博客也在很长时间没有再更新,有点对不起读者了。

年前第一次重构时,由于低估这套系统的复杂性再加上有些冒进,步子迈得有点大,出现了很多问题,不得不重新开始。这一次重构先易后难,步步为营,难题统一在后面解决,到现在已经完成了全部工程的百分之八十,后面的也没有太困难了,所以特地抽出时间小结一下。

1. 类库迁移

  直接拷贝到netcore 类库下,修改命名空间即可;

2. 迁移包(不同项目需要迁移的包不一下)

  using System.Web.Script.Serialization;  ---》using Nancy.Json;

 3. Action 跳转

  View 写法: 

await Component.InvokeAsync("IndexMapSpot", new { PageType = "show_page" })
// @*@{Html.Action("IndexMapSpot", "Matrix", new { PageType = "show_page" });}*@

定义实现IndexMapSpotViewComponent

namespace Techub.QHNY.Web.Components
{
    public class IndexMapSpotViewComponent : ViewComponent
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public IViewComponentResult Invoke(string PageType = "", string from = "0")
        {
            ViewBag.page = PageType;
            ViewBag.from = from;
            return View("~/Views/Matrix/IndexMapSpot.cshtml");
        }
    }
}
  1. JsonResult 数据
  2. System.Drawing 下面很多类已经不存在(如Bitmap),可以下载扩展包,例如:https://github.com/zkweb-framework/ZKWeb.System.Drawing,或:https://www.nuget.org/packages/System.Drawing.Common/
  3. Controller 中已经没有 OnResultXX() 的重写方法,解决方法:让 Controller 实现 IResultFilter 接口即可
  4. RouteData.GetRequiredString("controller") 方法已经不被支持,可以使用 RouteData.Values["controller"].ToString() 方法来取代
  5. Cookie 的写入方法如:
     Response.Cookies.Append("SMS", "1", new CookieOptions()
     {
         Expires = DateTime.Now.AddMinutes(2)
     });
  6. 例如 OnResultExecuting(ResultExecutingContext filterContext) 中的 filterContext.Controller 已经改为 object 类型,如果你确定使用的是默认的 Controller 的话,可以这样写:
    (filterContext.Controller as Controller).ViewData
  7. Controller 中的 Session["xx"] 访问方式改为 HttpContext.Session.GetString("xx")
  8. MvcHtmlString 变为 HtmlString,接口为 IHtmlContent
  9. [ValidateInput(false)] 标签已经不再需要添加:https://github.com/aspnet/Mvc/issues/324
  10. Response.ClearContent(); 已经不能使用, Response.BinaryWrite() 方法改为 Response.Body.Write()
  11. new UrlHelper(helper.ViewContext.RequestContext) 改为 new UrlHelper(helper.ViewContext)
  12. Request.UserHostName 改为 Request.Host.Value
  13. Request.Url.Host 改为 Request.Host,注意:通常会包含端口号,或使用:httpContext.Connection.RemoteIpAddress
  14. Request.UserHostAddress 改为 httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress
  15. HttpUnauthorizedResult 改名为 UnauthorizedResult
  16. Controller 的 OnAuthentication() 重写方法已经没有了
  17. HtmlHelper.AttributeEncode() 方法已失效
  18. Request..HttpMethod 改为 Request.Method
  19. Request.IsSecureConnection 可以使用 Request.IsHttps
  20. Request.Url.PathAndQuery 改为 Request.Path + Request.Query,可以自己写一个扩展方法进行封装
  21. Request.UrlReferrer 已经不被支持,可以自己封装:request.Headers["Referer"].ToString()
  22. Request.UserAgent 已经不被支持,可以自己封装:request.Headers["User-Agent"].ToString()
  23. Request.IsAjaxRequest 方法在.net core 中没有支持,可以自行扩展:
        /// <summary>
        /// Determines whether the specified HTTP request is an AJAX request.
        /// </summary>
        /// 
        /// <returns>
        /// true if the specified HTTP request is an AJAX request; otherwise, false.
        /// </returns>
        /// <param name="request">The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> parameter is null (Nothing in Visual Basic).</exception>
        public static bool IsAjaxRequest(this HttpRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (request.Headers != null)
                return request.Headers["X-Requested-With"] == "XMLHttpRequest";
            return false;
        }
    }

 

     注意:命名空间多数都会有变化,根据IDE提示添加即可。

给TA打赏
共{{data.count}}人
人已打赏
.NET

浅议.NET遗留应用改造

2022-7-4 17:24:43

.Net Core

个人web开发我选Asp.net core,你选谁?PHP?还是JSP?

2021-12-13 12:16:59

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
今日签到
有新私信 私信列表
搜索