为了更好的测试,更好的性能,Preview4带了一个新的请求返回值类型,这个新的类型中封装了所有的Http请求返回状态函数,还包括了返回成功后的几种数据类型,下面列举了几个常用的类型:
app.MapGet("/test_ok", () => { return TypedResults.Ok<Data>(new Data { Id = 1, Name = "测试产品", Price = 10.2m }); }); app.MapGet("/test_json", () => { return TypedResults.Json<Data>(new Data { Id = 1, Name = "测试产品", Price = 10.2m }); }); app.MapGet("/test_localredirect", () => { return TypedResults.LocalRedirect("/test_ok"); }); app.MapGet("/test_redirect", () => { return TypedResults.Redirect("https://www.google.com"); }); app.MapGet("/test_file", () => { var bytes = "这是一个测试"u8;//这个需要C#11,项目文件的PropertyGroup节点中增加<LangVersion>preview</LangVersion> return TypedResults.File(bytes, contentType: "text", fileDownloadName: "test.txt"); }); app.MapGet("/test_physicalfile", () => { return TypedResults.PhysicalFile(Directory.GetCurrentDirectory() + "/download.txt", contentType: "text", fileDownloadName: "download.txt"); });
同时也包括了SignIn和SignOut,在授权限时使用,相对于前一版的Results来说还是丰富了不少,比较如下:
![](/i/l/?n=23&i=blog/1101861/202212/1101861-20221205204212581-159797761.png)
标签:MapGet,TypedResults,return,Preview4,app,test,NET7 From: https://www.cnblogs.com/axzxs2001/p/16953462.html