.NET7 Preview4:重构的返回值TypedResults

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET7 Preview4:重构的返回值TypedResults相关的知识,希望对你有一定的参考价值。

为了更好的测试,更好的性能,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来说还是丰富了不少,比较如下:

以上是关于.NET7 Preview4:重构的返回值TypedResults的主要内容,如果未能解决你的问题,请参考以下文章

.NET7 Preview4之MapGroup

.NET7 Preview4 之OpenAPI swagger改进

.NET7 Preview4 之OpenAPI swagger改进

.NET7 Preview4 之OpenAPI swagger改进

宣布 .NET MAUI 支持 .NET 7 RC 2

重构:简化函数调用