.Net Core 2.2升级3.1的避坑指南(小结)

时间:2022-09-11 20:29:59

写在前面

  微软在更新.net core版本的时候,动作往往很大,使得每次更新版本的时候都得小心翼翼,坑实在是太多。往往是悄咪咪的移除了某项功能或者组件,或者不在支持xx方法,这就很花时间去找回需要的东西了,下面是个人在迁移.net core webapi项目过程中遇到的问题汇总:

开始迁移

1. 修改*.csproj项目文件

?
1
2
3
<targetframework>netcoreapp2.2</targetframework>
修改为
<targetframework>netcoreapp3.1</targetframework>

2 修改program

?
1
2
3
4
5
6
7
8
9
10
11
12
public static void main(string[] args)
    {
      createwebhostbuilder(args).build().run();
    }
 
    public static iwebhostbuilder createwebhostbuilder(string[] args) =>
        webhost.createdefaultbuilder(args)
          .usestartup<startup>().configureappconfiguration((hostingcontext, config) =>
          {
            config.addjsonfile($"你的json文件.json", optional: true, reloadonchange: true);
          }
          );

修改为

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(string[] args)
    {
      createhostbuilder(args).build().run();
    }
 
    public static ihostbuilder createhostbuilder(string[] args) =>
      host.createdefaultbuilder(args)
        .configurewebhostdefaults(webbuilder =>
        {
          webbuilder.usestartup<startup>()
                .configureappconfiguration((hostingcontext, config)=>
                {
                  config.addjsonfile($"你的json文件.json", optional: true, reloadonchange: true);
                });
        });

3.1 修改startup.configureservices

?
1
2
3
services.addmvc();
修改为
services.addcontrollers();

3.2 修改startup.configure

?
1
2
3
4
5
public void configure(iapplicationbuilder app, ihostingenvironment env)
 
修改为
using microsoft.extensions.hosting;
public void configure(iapplicationbuilder app, iwebhostenvironment env)

ihostingenvironment在3.0之后已被标记弃用。

路由配置:

?
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
app.usemvc(routes =>
        {
          routes.maproute(
            name: "areas",
            template: "{area:exists}/{controller=home}/{action=index}/{id?}"
          );
 
          routes.maproute(
            name: "default",
            template: "{controller=home}/{action=index}/{id?}"
          );
        });
 
修改为
 
      app.userouting();
      app.useendpoints(endpoints =>
      {
        endpoints.mapcontrollers();
        endpoints.mapcontrollerroute(
            name: "areas",
            pattern: "{area:exists}/{controller=home}/{action=index}/{id?}");
        endpoints.mapcontrollerroute(
            name: "default",
            pattern: "{controller=home}/{action=index}/{id?}");
      });

你以为结束了?还没。

  这时候你以为结束了,兴高采烈的去服务器装好runningtime和hosting相应的版本,运行……

.Net Core 2.2升级3.1的避坑指南(小结)

http error 500.30 – ancm in-process start failure

直接cmd,进入到发布目录,执行:

e:\你的路径>dotnet xxx.dll

显示详细错误

.Net Core 2.2升级3.1的避坑指南(小结)

而我的相应250代码行是:

?
1
services.addautomapper(appdomain.currentdomain.getassemblies());

搜索最新的automapper根本没更新或改变,所以不是这个组件的问题。

尝试下载补丁windows6.1-kb974405-x64.msu,无果……

卸载sdk重置,无果……

修改web.config,无果……

修改应用池32位,无果……

最后,查看发布:勾选上【删除现有文件】,解决……

.Net Core 2.2升级3.1的避坑指南(小结)

endpoint contains cors metadata, but a middleware was not found that supports cors.

  顺利可以启动项目之后,发现有些接口:

2020-06-29 10:02:23,357 [14] error system.string - 全局异常捕捉:异常:endpoint contains cors metadata, but a middleware was not found that supports cors.
configure your application startup by adding app.usecors() inside the call to configure(..) in the application startup code. the call to app.useauthorization() must appear between app.userouting() and app.useendpoints(...).

提示很明显,在.net core 2.2 的时候

?
1
app.usecors();

不是需要强制在指定位置的,在3.0之后需要设置在app.userouting和app.useendpoints 之间

?
1
2
3
4
5
app.userouting();//跨域
app.usecors(one);
app.usecors(two);
……
app.useendpoints(endpoints => ……

the json value could not be converted to system.int32. path……

  运行之后,有些接口没有数据返回,而有些直接报错了。原因又是爸爸把newtonsoft.json移除,使用内置的system.text.json,所以依赖于newtonsoft.json的组件将不可用,那么,只能手动添加。

?
1
install-package microsoft.aspnetcore.mvc.newtonsoftjson -version 3.1.5

然后添加引用

?
1
2
3
4
public void configureservices(iservicecollection services)
{
  services.addcontrollers().addnewtonsoftjson();
}

目前还不太建议你使用内置的序列化,因为实在太多功能或方法不支持,详细对比请参考 https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to

授权相关

  基于策略授权,我想在座的加班狗都是大同小异,在2.2以前:

?
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class policyhandler : authorizationhandler<policyrequirement>
  {
    /// <summary>
    /// 授权方式(cookie, bearer, oauth, openid)
    /// </summary>
    public iauthenticationschemeprovider schemes { get; set; }
 
    private iconfiguration _configuration;
 
    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="configuration"></param>
    /// <param name="schemes"></param>
    /// <param name="jwtapp"></param>
    public policyhandler(iconfiguration configuration, iauthenticationschemeprovider schemes)
    {
      schemes = schemes;
      _jwtapp = jwtapp;
      _configuration = configuration;
    }
 
    /// <summary>
    /// 授权处理
    /// </summary>
    /// <param name="context"></param>
    /// <param name="requirement"></param>
    protected override async task handlerequirementasync(authorizationhandlercontext context, policyrequirement requirement)
    {
      var httpcontext = (context.resource as authorizationfiltercontext).httpcontext;
 
      //获取授权方式
      var defaultauthenticate = await schemes.getdefaultauthenticateschemeasync();
      if (defaultauthenticate != null)
      {
        //验证签发的用户信息
        var result = await httpcontext.authenticateasync(defaultauthenticate.name);
        if (result.succeeded)
        {
          httpcontext.user = result.principal;
         
          //判断是否过期
          var expirationtime = datetime.parse(httpcontext.user.claims.singleordefault(s => s.type == claimtypes.expiration).value);
          if (expirationtime >= datetime.utcnow)
          {
             //你的校验方式
             //todo
            context.succeed(requirement);
          }
          else
          {
            handleblocked(context, requirement);
          }
          return;
        }
      }
      handleblocked(context, requirement);
    }
     
    /// <summary>
    /// 验证失败返回
    /// </summary>
    private void handleblocked(authorizationhandlercontext context, policyrequirement requirement)
    {
      var authorizationfiltercontext = context.resource as authorizationfiltercontext;
      authorizationfiltercontext.result = new microsoft.aspnetcore.mvc.jsonresult(new unauthorizativeresponse()) { statuscode = 202 };
      //不要调用 context.fail(),设置为403会显示不了自定义信息,改为accepted202,由客户端处理,;
      context.succeed(requirement);
    }
  }

然后发现升级到3.0之后,

?
1
var httpcontext = (context.resource as authorizationfiltercontext).httpcontext;

3.0不再支持返回authorizationfiltercontext,而是返回的是routeendpoint,这句代码就会报错,所以修改的方式就是注入ihttpcontextaccessor,从里面获取httpcontext,这里就不用演示了吧。

并修改policyhandler校验失败时候调用的方法:

?
1
2
3
4
5
6
7
/// <summary>
    /// 验证失败返回
    /// </summary>
    private void handleblocked(authorizationhandlercontext context, policyrequirement requirement)
    {
      context.fail();
    }

并在startup.configureservices修改

?
1
services.addhttpcontextaccessor();

在addjwtbearer中

?
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
.addjwtbearer(s =>
      {
        //3、添加 jwt bearer
        s.tokenvalidationparameters = new tokenvalidationparameters
        {
          validissuer = issuer,
          validaudience = audience,
          issuersigningkey = key,
          //允许的服务器时间偏差的偏移量
          clockskew = timespan.fromseconds(5),
          validatelifetime = true
        };
        s.events = new jwtbearerevents
        {
          onauthenticationfailed = context =>
          {
            //token 过期
            if (context.exception.gettype() == typeof(securitytokenexpiredexception))
            {
              context.response.headers.add("token-expired", "true");
            }
            return task.completedtask;
          },
          onchallenge = context =>
          {
            context.handleresponse();
            context.response.statuscode = statuscodes.status200ok;
            context.response.contenttype = "application/json";
            //无授权返回自定义信息
            context.response.writeasync(jsonconvert.serializeobject(new unauthorizativeresponse()));
            return task.completedtask;
          }
        };
      });

unauthorizativeresponse 是自定义返回的内容。

startup.configure中启用authentication,注意顺序

?
1
2
3
4
5
6
7
8
9
app.userouting();
//跨域
app.usecors(one);
app.usecors(two);
……
//启用 authentication
app.useauthorization();
app.useauthentication();
app.useendpoints(endpoints => ……

也必须在app.userouting和app.useendpoints之间。

文件下载

  单独封装的httpcontext下载方法:

?
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
public static void downloadfile(this httpcontext context,string filename, byte[] filebyte, string contenttype = "application/octet-stream")
    {
      int buffersize = 1024;
      
      context.response.contenttype = contenttype;
      context.response.headers.append("content-disposition", "attachment;filename=" + httputility.urlencode(filename));
      context.response.headers.append("charset", "utf-8");
      context.response.headers.append("access-control-expose-headers", "content-disposition");
     
      //context.response.headers.append("access-control-allow-origin", "*");
      //使用filestream开始循环读取要下载文件的内容
      using (stream fs = new memorystream(filebyte))
      {
        using (context.response.body)
        {
          long contentlength = fs.length;
          context.response.contentlength = contentlength;
 
          byte[] buffer;
          long hasread = 0;
          while (hasread < contentlength)
          {
            if (context.requestaborted.iscancellationrequested)
            {
              break;
            }
            
            buffer = new byte[buffersize];
            //从下载文件中读取buffersize(1024字节)大小的内容到服务器内存中
            int currentread = fs.read(buffer, 0, buffersize);
            context.response.body.write(buffer, 0, currentread);
            context.response.body.flush();
            hasread += currentread;
          }
        }
      }
    }

下载的时候发现以下错误:synchronous operations are disallowed. call writeasync or set allowsynchronousio to true instead.

?
1
2
3
4
2020-06-29 14:18:38,898 [109] error system.string - system.invalidoperationexception: synchronous operations are disallowed. call writeasync or set allowsynchronousio to true instead.
  at microsoft.aspnetcore.server.iis.core.httpresponsestream.write(byte[] buffer, int32 offset, int32 count)
  at microsoft.aspnetcore.server.iis.core.wrappingstream.write(byte[] buffer, int32 offset, int32 count)
  at digitalcertificatesystem.common.extensions.httpcontextextension.downloadfile(httpcontext context, string filename, byte[] filebyte, string contenttype) in ……

意思不运行同步操作,修改为

?
1
context.response.body.writeasync(buffer, 0, currentread);

这才顺利完成了更新。真的太坑了,不过也感觉微软的抽象化做得很好,按需引入,减少项目的冗余。

更多升级指南请参考“孙子兵法”:https://docs.microsoft.com/zh-cn/aspnet/core/migration/22-to-30?view=aspnetcore-2.1&tabs=visual-studio

作者:eminemjk(山治先生)
出处:https://www.cnblogs.com/eminemjk/

到此这篇关于.net core 2.2升级3.1的避坑指南(小结)的文章就介绍到这了,更多相关.net core 2.2升级3.1内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/EminemJK/p/13206747.html