LightPoint.Foundation.Result
1.2.0
dotnet add package LightPoint.Foundation.Result --version 1.2.0
NuGet\Install-Package LightPoint.Foundation.Result -Version 1.2.0
<PackageReference Include="LightPoint.Foundation.Result" Version="1.2.0" />
paket add LightPoint.Foundation.Result --version 1.2.0
#r "nuget: LightPoint.Foundation.Result, 1.2.0"
// Install LightPoint.Foundation.Result as a Cake Addin
#addin nuget:?package=LightPoint.Foundation.Result&version=1.2.0
// Install LightPoint.Foundation.Result as a Cake Tool
#tool nuget:?package=LightPoint.Foundation.Result&version=1.2.0
简要说明
LightPoint.Foundation.Result 是用于在 .net core 中实现 Result 模式,用于在 Light Point 架构设计中,常规设计中的方法或者服务返回值的包装(Result)处理,具体来说,构建一个可支持 http 代码可以直接映射的抽象结果,在需要的时候使用。
本项目是参考 Steve Smith 的 Result 的项目来具体实现的。
针对的问题
许多服务上的方法需要返回某种类型的值。例如,它们可能在查找一些数据并返回一组结果或单个对象。它们可能在创建某个东西,将其保存下来,然后返回它。通常,这类方法的实现方式如下:
public Customer GetCustomer(int customerId)
{
// more logic
return customer;
}
public Customer CreateCustomer(string firstName, string lastName)
{
// more logic
return customer;
}
这种方法在我们只关注正常流程的情况下工作得很好。但是,如果存在多种可能的异常故障隐含其中,而且并非所有异常故障都适合通过异常来处理,那么会发生什么情况呢?
- 如果 customerId 缺少,将会发生?
- customer 对象数据中
lastName
是必须的,但没有提供,将会发生什么? - 如果当前用户不能处理新增用户的操作,将会发生什么 ?
处理这些顾虑的常规方法是使用异常。一般通过 try,为每种不同的异常故障抛出不同的异常,然后 catch 来具体处理异常故障。事实上,这给客户端代码带来了繁琐的设计要求,并导致许多异常,对于设计来说并非一定属于“异常情况”的事情。如下所示:
[HttpGet]
public async Task<ActionResult<CustomerDTO>> GetCustomer(int customerId)
{
try
{
var customer = _repository.GetById(customerId);
var customerDTO = CustomerDTO.MapFrom(customer);
return Ok(customerDTO);
}
catch (NullReferenceException ex)
{
return NotFound();
}
catch (Exception ex)
{
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}
另一种方法是返回一个元组(Tuple)
,其中包括预期的结果以及其他内容,比如状态码和额外的故障模式元数据。虽然 Tuple 在处理个体的、灵活的响应时非常出色,但它们并不适合用于提供单一的、标准的、可重用的问题解决方案。
Result 模式提供了一种标准的、可重用的方法,以易于映射到 API 响应类型的方式从 .NET 服务返回成功以及多种非成功响应。这种方式使得处理成功和多种类型的非成功响应变得更加统一和便捷。
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
-
net8.0
- LightPoint.Foundation.Base (>= 1.2.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on LightPoint.Foundation.Result:
Package | Downloads |
---|---|
LightPoint.Foundation.Result.AspNetCore
在 .net core 中实现 Result 模式,用于在 Light Point 架构设计中,常规设计中的方法或者服务返回值的包装(Result)处理,具体来说,构建一个可支持 http 代码可以直接映射的抽象结果,在需要的时候使用。 本项目是参考 Steve Smith 的 [Result](https://github.com/ardalis/Result) 的项目来具体实现的。 |
GitHub repositories
This package is not used by any popular GitHub repositories.