1.0k sao GitHub và vẫn tăng — ardalis/Result là dự án C# mà TopGit đang theo dõi trên nền tảng. A result abstraction that can be mapped to HTTP response codes if needed.
Tóm tắt dựng từ metadata GitHub của chính dự án — chưa có bài review TopGit. Trang sẽ tự động cập nhật khi bài review đầy đủ được xuất bản.
VÌ SAO CHƯA CÓ REVIEW
TopGit viết bài đầy đủ cho repo có nhiều sao nhất và được yêu cầu nhiều nhất. Trang này là snapshot trong thời gian chờ — xem README gốc ở tab READ ME.
A result abstraction that can be mapped to HTTP response codes if needed.
Docs
Docs are located in the /docs folder and available online at result.ardalis.com Please add issues for new docs requests and pull requests for docs issues are welcome!
Learn More
Getting Started With Ardalis.Result
Transforming Results With the Map Method
Avoid Using Exceptions to Determine API Status Codes and Responses
Fluent Validation in MediatR with Results
What Problem Does This Address?
Many methods on service need to return some kind of value. For instance, they may be looking up some data and returning a set of results or a single object. They might be creating something, persisting it, and then returning it. Typically, such methods are implemented like this:
public Customer GetCustomer(int customerId)
{
// more logic
return customer;
}
public Customer CreateCustomer(string firstName, string lastName)
{
// more logic
return customer;
}
This works great as long as we're only concerned with the happy path. But what happens if there are multiple failure modes, not all of which make sense to be handled by exceptions?
What happens if customerId is not found?
What happens if required lastName is not provided?
What happens if the current user doesn't have permission to create new customers?
The standard way to address these concerns is with exceptions. Maybe you throw a different exception for each different failure mode, and the calling code is then required to have multiple catch blocks designed for each type of failure. This makes life painful for the consumer, and results in a lot of exceptions for things that aren't necessarily exceptional. Like this:
[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);
}
}
Another approach is to return a Tuple of the expected result along with other things, like a status code and additional failure mode metadata. While tuples can be great for individual, flexible responses, they're not as good for having a single, standard, reusable approach to a problem.
The Result pattern provides a standard, reusable way to return both success as well as multiple kinds of non-success responses from .NET services in a way that can easily be mapped to API response types. Although the Ardalis.Result package has no dependencies on ASP.NET Core and can be used from any .NET Core application, the Ardalis.Result.AspNetCore companion package includes resources to enhance the use of this pattern within ASP.NET Core web API applications.
Sample Usage
Creating a Result
The sample folder includes some examples of how to use the project. Here are a couple of simple uses.
Imagine the snippet below is defined in a domain service that retrieves WeatherForecasts. When compared to the approach described above, this approach uses a result to handle common failure scenarios like missing data denoted as NotFound and or input validation errors denoted as Invalid. If execution is successful, the result will contain the random data generated by the final return statement.
public Result<IEnumerable<WeatherForecast>> GetForecast(ForecastRequestDto model)
{
if (model.PostalCode == "NotFound") return Result<IEnumerable<WeatherForecast>>.NotFound();
// validate model
if (model.PostalCode.Length > 10)
{
return Result<IEnumerable<WeatherForecast>>.Invalid(new List<ValidationError> {
new ValidationError
{
Identifier = nameof(model.PostalCode),
ErrorMessage = "PostalCode cannot exceed 10 characters."
}
});
}
var rng = new Random();
return new Result<IEnumerable<WeatherForecast>>(Enumerable.Range(1, 5)
.Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray());
}
Translating Results to ActionResults
Continuing with the domain service example from the previous section, it's important to show that the domain service doesn't know about ActionResult or other MVC/etc types. But since it is using a Result<T> abstraction, it can return results that are easily mapped to HTTP status codes. Note that the method above returns a Result<IEnumerable<WeatherForecast> but in some cases, it might need to return an Invalid result, or a NotFound result. Otherwise, it returns a Success result with the actual returned value (just like an API would return an HTTP 200 and the actual result of the API call).
You can apply the [TranslateResultToActionResult] attribute to an API Endpoint (or controller action if you still use those things) and it will automatically translate the Result<T> return type of the method to an ActionResult<T> appropriately based on the Result type.
[TranslateResultToActionResult]
[HttpPost("Create")]
public Result<IEnumerable<WeatherForecast>> CreateForecast([FromBody]ForecastRequestDto model)
{
return _weatherService.GetForecast(model);
}
Alternatively, you can use the ToActionResult helper method within an endpoint to achieve the same thing:
Similar to how the ToActionResult extension method translates Ardalis.Results to ActionResults, the ToMinimalApiResult translates results to the new Microsoft.AspNetCore.Http.ResultsIResult types in .NET 6+. The following code snippet demonstrates how one might use the domain service that returns a Result<IEnumerable<WeatherForecast>> and convert to a Microsoft.AspNetCore.Http.Results instance.
The full Minimal API sample can be found in the sample folder.
Mapping Results From One Type to Another
A common use case is to map between domain entities to API response types usually represented as DTOs. You can map a result containing a domain entity to a Result containing a DTO by using the Map method. The following example calls the method _weatherService.GetSingleForecast which returns a Result<WeatherForecast> which is then converted to a Result<WeatherForecastSummaryDto> by the call to Map. Then, the result is converted to an ActionResult<WeatherForecastSummaryDto> using the ToActionResult helper method.
[HttpPost("Summary")]
public ActionResult<WeatherForecastSummaryDto> CreateSummaryForecast([FromBody] ForecastRequestDto model)
{
return _weatherService.GetSingleForecast(model)
.Map(wf => new WeatherForecastSummaryDto(wf.Date, wf.Summary))
.ToActionResult(this);
}
Chaining Result Operations with Bind and BindAsync
You can chain together multiple operations that return Result<T> using the Bind and BindAsync methods. This allows you to perform a sequence of operations where each operation can fail, and if any operation fails, the subsequent operations will not be executed. This can be useful for eliminating checking for success after each Result operation with a more readable and maintainable chain of operations.
[HttpPost("Summary")]
public async Task<ActionResult<WeatherForecastSummaryDto>> CreateSummaryForecast([FromBody] ForecastRequestDto model)
{
var result1 = await _weatherService.GetSingleForecast(model);
if (!result1.IsSuccess)
{
return result1.ToActionResult(this);
}
var result2 = await _weatherService.GetForecastDetailsAsync(result1.Value.Id);
return result2
.Map(details => new WeatherForecastSummaryDto(details.Date, details.Summary))
.ToActionResult(this);
}
With the Bind and BindAsync methods, you can simplify this code by chaining the operations together. The following example demonstrates how to use BindAsync to achieve the same result in a more concise manner:
In this example, if GetSingleForecast returns a failure result, GetForecastDetailsAsync will not be called, and the failure will propagate through the chain. If all operations succeed, the final result will be mapped to a WeatherForecastSummaryDto and returned as an ActionResult.
ASP.NET API Metadata
By default, Asp Net Core and API Explorer know nothing about [TranslateResultToActionResult] and what it is doing. To reflect [TranslateResultToActionResult] behavior in metadata generated by API Explorer (which is then used by tools like Swashbuckle, NSwag etc.), you can use ResultConvention:
This will add [ProducesResponseType] for every known ResultStatus to every endpoint marked with [TranslateResultToActionResult].
To customize ResultConvention behavior, one may use the AddResultConvention method:
ResultConvention will add [ProducesResponseType] for every result status configured in ResultStatusMap. AddDefaultMap() maps every known ResultType, so if you want to exclude certain ResultType from being listed (e.g. your app doesn't have authentication and authorization, and you don't want 401 and 403 to be listed as SupportedResponseType) you can do this:
We can use Ardalis.Result.FluentValidation on a service with FluentValidation like that:
public async Task<Result<BlogCategory>> UpdateAsync(BlogCategory blogCategory)
{
if (Guid.Empty == blogCategory.BlogCategoryId) return Result<BlogCategory>.NotFound();
var validator = new BlogCategoryValidator();
var validation = await validator.ValidateAsync(blogCategory);
if (!validation.IsValid)
{
return Result<BlogCategory>.Invalid(validation.AsErrors());
}
var itemToUpdate = (await GetByIdAsync(blogCategory.BlogCategoryId)).Value;
if (itemToUpdate == null)
{
return Result<BlogCategory>.NotFound();
}
itemToUpdate.Update(blogCategory.Name, blogCategory.ParentId);
return Result<BlogCategory>.Success(await _blogCategoryRepository.UpdateAsync(itemToUpdate));
}
Getting Started
If you're building an ASP.NET Core Web API you can simply install the Ardalis.Result.AspNetCore package to get started. Then, apply the [TranslateResultToActionResult] attribute to any actions or controllers that you want to automatically translate from Result types to ActionResult types.
ardalis/Result có 1.0k sao GitHub — tải lại trang để xem số mới nhất, hoặc xem trực tiếp github.com/ardalis/Result. TopGit phản chiếu số sao của GitHub nhưng không cam kết đến từng phút.
ardalis/Result có những chủ đề gì?
GitHub topics của ardalis/Result: "csharp", "design-patterns", "domain-driven-design", "dotnet", "dotnet-core", "functional", "hacktoberfest", "maybe", "result". TopGit xếp repo vào nhóm Backend.
ardalis/Result còn đang phát triển không?
Commit gần nhất trên ardalis/Result là 4 tháng trước (theo timestamp GitHub). Repo có 128 fork — một chỉ báo về mức độ quan tâm của cộng đồng.
ardalis/Result là gì?
ardalis/Result (ardalis/Result) là dự án C# trên GitHub. Theo mô tả gốc: A result abstraction that can be mapped to HTTP response codes if needed.
ardalis/Result so với các dự án Backend khác thế nào?
ardalis/Result được TopGit xếp vào nhóm Backend, với 1.0k sao GitHub và viết bằng C#. Xem trang chủ đề Backend trên TopGit để so sánh với các dự án tương tự theo số sao và mức độ hoạt động.
ardalis/Result viết bằng ngôn ngữ gì?
ardalis/Result chủ yếu viết bằng C#. Trường "language" của GitHub dựa trên phần lớn byte ở nhánh mặc định.
Vì sao ardalis/Result được xếp vào nhóm Backend?
TopGit xếp ardalis/Result vào nhóm Backend dựa trên GitHub topics và mô tả của repo (gắn thẻ: "csharp", "design-patterns", "domain-driven-design"). Việc phân loại dựa trên metadata thật của repo, không phải đoán theo cảm tính biên tập.
Đọc đầy đủ README ở tab phía trên.
Chưa chắc Result có hợp với bạn?
Để ChatGPT, Claude hoặc Perplexity tìm hiểu giúp — bấm bên dưới và xem AI nói gì về Result.