ASP.NET MVC升级到ASP.NET Core MVC踩坑小结

写在前面

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

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

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

详细内容

类库部分

类库部分的迁移应该是最简单的了,我是创建了一个新的类库,然后把代码copy过去,很少有地方需要修改,当然了有一些引用的第三方类库需要特殊对待,如Automapper、Autofac、FluentValidation等,这些也很简单,看看文档就行。

.NET Framework中,会有一些常用的封装库,如Session、Cookie和HttpRuntime等,这些变化比较大,所以自己在Startup中启用。

  • Session:

    • Startup.Configure:

      app.UseSession(new SessionOptions
      {Cookie = new CookieBuilder{},IdleTimeout = TimeSpan.FromSeconds(1),IOTimeout = Timeout.InfiniteTimeSpan
      });
      
    • Startup.ConfigureServices:

      services.AddSession();
      
    • 使用Session,可以通过HttpContext调用:

      HttpContext.Session.SetString("sessionId", sessionValue);
      HttpContext.Session.GetString("sessionId");
      context.Session.Remove("sessionId");
      
  • Cookie:

  • Response.Cookies.Append("User", "1", new CookieOptions()
    {Expires = DateTime.Now.AddMinutes(10)
    });//新增操作
    Response.Cookies.Delete("User");//删除操作
    
  • HttpRuntime的使用,可以通过IMemoryCache替换,具体的使用方法可参考MSDN(链接:https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-3.1)

  • System.Drawing已经不存在了,我使用的是ZKWeb.System.Drawing,基本上类名、枚举名没变化,只是命名空间Drawing变成了DrawingCore

  • 依赖注入部分全部迁移到Startup.ConfigureServices

  • Controller部分

    顺便说一下,静态资源部分,如JS、CSS、Image、Font这些复制到wwwroot目录上,另外app.UseStaticFiles();会在模板中出现。

    1、获取Controller及Action信息,可以通过RouteData.Values["controller"].ToString(),RouteData.Values["action"].ToString()

    2、很多的信息都放到了Request.Header[“”]中,如果之前可以用过Request直接点出来的,但是现在点不出来了,可以尝试使用这种方式,说不准会有意外惊喜。另外有一个相关的常量在这里出示一下,使用方式即Request.Header[HeaderNames.Authority],当然Request.HttpMethod 改为了 Request.Method。

    public static class HeaderNames
    {public static readonly string Accept;public static readonly string AcceptCharset;public static readonly string AcceptEncoding;public static readonly string AcceptLanguage;public static readonly string AcceptRanges;public static readonly string AccessControlAllowCredentials;public static readonly string AccessControlAllowHeaders;public static readonly string AccessControlAllowMethods;public static readonly string AccessControlAllowOrigin;public static readonly string AccessControlExposeHeaders;public static readonly string AccessControlMaxAge;public static readonly string AccessControlRequestHeaders;public static readonly string AccessControlRequestMethod;public static readonly string Age;public static readonly string Allow;public static readonly string Authority;public static readonly string Authorization;public static readonly string CacheControl;public static readonly string Connection;public static readonly string ContentDisposition;public static readonly string ContentEncoding;public static readonly string ContentLanguage;public static readonly string ContentLength;public static readonly string ContentLocation;public static readonly string ContentMD5;public static readonly string ContentRange;public static readonly string ContentSecurityPolicy;public static readonly string ContentSecurityPolicyReportOnly;public static readonly string ContentType;public static readonly string Cookie;public static readonly string CorrelationContext;public static readonly string Date;public static readonly string DNT;public static readonly string ETag;public static readonly string Expect;public static readonly string Expires;public static readonly string From;public static readonly string Host;public static readonly string IfMatch;public static readonly string IfModifiedSince;public static readonly string IfNoneMatch;public static readonly string IfRange;public static readonly string IfUnmodifiedSince;public static readonly string KeepAlive;public static readonly string LastModified;public static readonly string Location;public static readonly string MaxForwards;public static readonly string Method;public static readonly string Origin;public static readonly string Path;public static readonly string Pragma;public static readonly string ProxyAuthenticate;public static readonly string ProxyAuthorization;public static readonly string Range;public static readonly string Referer;public static readonly string RequestId;public static readonly string RetryAfter;public static readonly string Scheme;public static readonly string SecWebSocketAccept;public static readonly string SecWebSocketKey;public static readonly string SecWebSocketProtocol;public static readonly string SecWebSocketVersion;public static readonly string Server;public static readonly string SetCookie;public static readonly string Status;public static readonly string StrictTransportSecurity;public static readonly string TE;public static readonly string TraceParent;public static readonly string TraceState;public static readonly string Trailer;public static readonly string TransferEncoding;public static readonly string Translate;public static readonly string Upgrade;public static readonly string UpgradeInsecureRequests;public static readonly string UserAgent;public static readonly string Vary;public static readonly string Via;public static readonly string Warning;public static readonly string WebSocketSubProtocols;public static readonly string WWWAuthenticate;public static readonly string XFrameOptions;
    }
    

    3、Request.IsAjaxRequest

    这个已经不存在了,可以自行实现。

    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;
    }
    

    4、Area注册

    之前的AreaRegistration已经不存在,如果需要设置Area,可以在每个Controller上设置[Area(“Admin”)],路由处的注册可以考虑如下方式,

    app.UseEndpoints(endpoints =>
    {endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");endpoints.MapControllerRoute(name: "areas",pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    });
    

    5、AbsoluteUri也已经不存在了,但是可以通过如下三个方法取代:

    /// <summary>/// Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString)/// suitable only for display. This format should not be used in HTTP headers or other HTTP operations./// </summary>/// <param name="request">The request to assemble the uri pieces from.</param>/// <returns>The combined components of the request URL in a fully un-escaped form (except for the QueryString)/// suitable only for display.</returns>public static string GetDisplayUrl(this HttpRequest request);/// <summary>Returns the relative URI.</summary>/// <param name="request">The request to assemble the uri pieces from.</param>/// <returns>The path and query off of <paramref name="request" />.</returns>public static string GetEncodedPathAndQuery(this HttpRequest request);/// <summary>/// Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers/// and other HTTP operations./// </summary>/// <param name="request">The request to assemble the uri pieces from.</param>/// <returns>The encoded string version of the URL from <paramref name="request" />.</returns>public static string GetEncodedUrl(this HttpRequest request);
    

    6、过滤器

    之前继承ActionFilterAttribute,现在实现IActionFilter,注册方式为services.AddMvc(o=>o.Filters.Add(new XX())),当然之前的很多过滤器或者Controller基类方法已经不存在了,如Controller OnAuthentication。

    IResultFilter中的OnResultExecuting(ResultExecutingContext filterContext)需要通过filterContext.Controller as Controller来获取默认的Controller。

    最后有一个比较重要的类ActionDescriptorControllerDescriptor继承自ActionDescriptor,这里可以通过类型转换获取相关信息。

    之前有很多的FilterAttribute也可以通过中间件来取代。


    7、Action上被去掉的Attribute,如[ValidateInput(false)],[ChildActionOnly]

    View部分

    1、页面基类型及扩展

    之前我们创建页面基类型,是通过继承System.Web.Mvc.WebViewPage<TModel>来实现,现在我们可以通过RazorPage<TModel>来取代。

    扩展HtmlHelper也换成了IHtmlHelper接口。HtmlString也替换了MvcHtmlString,更上层也以接口方式来取代IHtmlContent。


    2、Ajax.BeginForm换成了<form asp-controller="DistributorGrade" asp-action="Save" id="addform" data-ajax="true" data-ajax-method="post" data-ajax-begin="begin" data-ajax-success="success">。当前.NET Core 依然支持Html.BeginForm,不过我建议大家有时间的时候都替换一下,具体请参考下一条。


    3、第2条出现的asp-action等是通过Razor Tag Helpers来实现的,很多的自定义需要加入到_ViewImports.cshtml,当然一些引用也可以统一放到这里,如@using Microsoft.AspNetCore.Routing,这样就可以在当前的Area中作为全局引用了。

    Razor Tag Help是一个十分重要的功能,它使得.NET Core MVC的开发更像是在写Html语言,更加的清晰,更加具有生产力。


    如@Html.TextBoxFor()可以用通过<input asp-for=””/>替换,以下图片摘自MSDN:

    Framework MVC的写法

    Core MVC的写法

    一些Tag Help集锦:(引用链接:https://docs.microsoft.com/en-US/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1


    Built-in ASP.NET Core Tag Helpers

    Anchor Tag Helper

    Cache Tag Helper

    Component Tag Helper

    Distributed Cache Tag Helper

    Environment Tag Helper

    Form Tag Helper

    Form Action Tag Helper

    Image Tag Helper

    Input Tag Helper

    Label Tag Helper

    Link Tag Helper

    Partial Tag Helper

    Script Tag Helper

    Select Tag Helper

    Textarea Tag Helper

    Validation Message Tag Helper

    Validation Summary Tag Helper

    4、@Html.Action和@Html.RenderAction可以通过ViewComponents来取代

    public class XXXXViewComponent : ViewComponent
    {public IViewComponentResult Invoke(){return this.View("");}
    }
    

    调用方式是await Component.InvokeAsync(“XXXXViewComponent”),详情请点击链接


    5、@MvcHtmlString.Create()可以使用new Microsoft.AspNetCore.Html.HtmlString()取代

    6、IP地址可以通过HttpRequest.HttpContext.Connection.RemoteIpAddress获取

    7、之前通过@helper 定义页面的函数,这个已经被去掉了,现在可以通过@functions来取代

    小结

    限于篇幅,先总结这么多,系统尚未完全结束,不过升级到.NET Core是一个非常棒的过程,可以更好地体验.NET Core的强大。如果小伙伴在升级过程中也遇到了很多问题,希望这篇文章可以给大家一些帮助,另外我没有写到的,大家可以留个言,我统一收集一下。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/310801.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

用函数求C15的值C语言,南开19春学期(1503、1509、1603、1609、1703)《C语言程序设计》在线作业-1辅导资料.docx...

南开19春学期(1503、1509、1603、1609、1703)《C语言程序设计》在线作业-1辅导资料.docx 南开19春学期(1503、1509、1603、1609、1703)C语言程序设计在线作业-11、D 2、B 3、C 4、A 5、D 一、单选题共40题&#xff0c;80分1、以下对一维整型数组 a 的正确说明是 Aint a10 ;Bint…

LeetCode 563二叉树的坡度-简单

给定一个二叉树&#xff0c;计算 整个树 的坡度 。 一个树的 节点的坡度 定义即为&#xff0c;该节点左子树的节点之和和右子树节点之和的 差的绝对值 。如果没有左子树的话&#xff0c;左子树的节点之和为 0 &#xff1b;没有右子树的话也是一样。空结点的坡度是 0 。 整个树…

c语言简单快速排序原理,C语言之简单快速排序

快速排序是一种对冒泡排序的改进&#xff0c;运用了二分的思想&#xff0c;提高了效率&#xff0c;元素的交换是跳跃式的&#xff0c;更适合用在数组这样方便随机读取的顺序结构&#xff0c;平均时间复杂度NlogN。#include #include /*快速排序*/void input(int*,int);void out…

LeetCode 501二叉搜索树中的众数-简单

给定一个有相同值的二叉搜索树&#xff08;BST&#xff09;&#xff0c;找出 BST 中的所有众数&#xff08;出现频率最高的元素&#xff09;。 假定 BST 有如下定义&#xff1a; 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值…

CIO/CTO都应该掌握和了解的EA(企业架构)

我们已进入数字化技术推动的第四次工业革命&#xff0c;是以工业互联网建设为标志。单纯从IT的视角管理信息化系统让许多企业深陷管理困境&#xff0c;解决问题也是按下葫芦浮起瓢。实际上&#xff0c;IT的服务对象是企业的战略、组织、管理、流程等一系列的要素&#xff0c;因…

c语言火车票管理系统源代码2000行,C语言教务管理系统[2000行代码].doc

专业资料精心整理C语言教务管理系统一、程序结构图二、程序运行截图1. 个人信息简介2. 修改颜色3. 注册界面4. 信息保存至文件5. 登录界面6. 管理员录入信息7. 学生信息录入8. 学生成绩录入9. 学生课程表录入10. 学生信息查询界面11学生信息查询12. 学生成绩查询13. 学生课表查…

LeetCode 530二叉搜索树的最小绝对值差-简单

给你一棵所有节点为非负值的二叉搜索树&#xff0c;请你计算树中任意两节点的差的绝对值的最小值。 示例&#xff1a; 输入&#xff1a; 1\3/2输出&#xff1a; 1 解释&#xff1a; 最小绝对差为 1&#xff0c;其中 2 和 1 的差的绝对值为 1&#xff08;或者 2 和 3&#xf…

扛并发主力军,引入应用层缓存

1.背景缓存的使用一定是今后开发中100%会用到的技术&#xff0c;尤其是Redis相关的问题&#xff0c;如果面试官不问我我几个缓存相关的问题&#xff0c;那我觉得我可能是去了个假的互联网公司。这里考虑到有些初学者刚刚出校园或者自学中&#xff0c;准许我多费口舌介绍下关于缓…

c语言筛法求一个范围内的素数,运用埃拉托色尼筛法求解一定范围内的素数.docx...

#includetypedef struct Node{int data;struct Node *link;}LinkList;void buildList(int max,LinkList *&head){//构建链表函数LinkList *l,*p;int i;head(LinkList*)malloc(sizeof(LinkList));head->linkNULL;lhead;for(i2;i<max;i){p(LinkList*)malloc(sizeof(Lin…

LeetCode 783二叉搜索树节点最小距离-简单

给你一个二叉搜索树的根节点 root &#xff0c;返回 树中任意两不同节点值之间的最小差值 。 示例 1&#xff1a; 输入&#xff1a;root [4,2,6,1,3] 输出&#xff1a;1 示例 2&#xff1a; 输入&#xff1a;root [1,0,48,null,null,12,49] 输出&#xff1a;1 提示&…

二级c语言作答文件不存在,全国计算机等级考试二级C语言上机考试题库及答案...

希望对有需要的人有帮助第1套 一、填空给定函数的功能是调用fun函数建立班级通讯录。通讯录记录每位学生的编号&#xff0c;姓名和电话号码。班级的人数和学生的信息从键盘读入&#xff0c;每个人的信息作为一个数据块写到名为答案yfile5.dat的二进制文件中。答案:1. STYPE 2. …

使用 VMware + win10 + vs2019 从零搭建双机内核调试环境

我在前面的文章——《使用 VMware win10 VirtualKD windbg 从零搭建双机内核调试环境》分享了使用 windbg 进行双机内核调试的环境搭建的步骤。有小伙伴儿留言说&#xff1a;在使用 vs 进行双机内核调试的时候&#xff0c;总是连不上。希望能发一篇使用 vs 进行双机内核调试…

LeetCode 617合并二叉树-简单

给定两个二叉树&#xff0c;想象当你将它们中的一个覆盖到另一个上时&#xff0c;两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠&#xff0c;那么将他们的值相加作为节点合并后的新值&#xff0c;否则不为 NULL 的节点将直…

配合理lcd的c语言小游戏,C语言源程序LCD.doc

C语言源程序LCDC语言源程序//******** 小波电子工作室 All rights reserved******//******** 个人主页&#xff1a;/niejinbo **//******** 文 件 名&#xff1a; lcd_0712.c **************//******** 功能概要&#xff1a; LCD液晶显示字符 ***********//******** MCU: STC89…

C#中的9个“黑魔法”与“骚操作”

C#中的9个“黑魔法”与“骚操作”我们知道 C#是非常先进的语言&#xff0c;因为是它很有远见的“语法糖”。这些“语法糖”有时过于好用&#xff0c;导致有人觉得它是 C#编译器写死的东西&#xff0c;没有道理可讲的——有点像“黑魔法”。那么我们可以看看 C#这些高级语言功能…

LeetCode 872叶子相似的树-简单

请考虑一棵二叉树上所有的叶子&#xff0c;这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。 举个例子&#xff0c;如上图所示&#xff0c;给定一棵叶值序列为 (6, 7, 4, 9, 8) 的树。 如果有两棵二叉树的叶值序列是相同&#xff0c;那么我们就认为它们是 叶相似 的。 …

android圆形变方形动画,CSS3 简单的圆形/方形变形动画

CSS语言&#xff1a;CSSSCSS确定html,body {width: 100%;height: 100%;background-color: #221e40;}*,*:after,*::before {box-sizing: border-box;}.centered {width: 100%;height: 100px;position: absolute;top: 50%;margin-top: -50px;}.morph {width: 100%;height: 100px;…

.NET Core开发实战(第35课:MediatR:让领域事件处理更加优雅)--学习笔记

35 | MediatR&#xff1a;让领域事件处理更加优雅核心对象IMediatorINotificationINotificationHandler这两个与之前的 Request 的行为是不一样的&#xff0c;接下来看一下代码internal class MyEvent : INotification {public string EventName { get; set; } }internal class…

LeetCode 559N叉树的最大深度-简单

给定一个 N 叉树&#xff0c;找到其最大深度。 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。 N 叉树输入按层序遍历序列化表示&#xff0c;每组子节点由空值分隔&#xff08;请参见示例&#xff09;。 示例 1&#xff1a; 输入&#xff1a;root [1,null,3,…