Похожие чаты

How do you guys transfer codes and stuff via diff

layers of the projects?

i have made this model to pass data from business to controller public class APIResponse<T>(int success, string message, T data, List<string> errors = null)
{
public int Success { get; set; } = success;
public string Message { get; set; } = message;
public List<string> Errors { get; set; } = errors ?? [];
public T Data { get; set; } = data;
}

calling it like
[HttpPost]
public async Task<IActionResult> Something(ContactRequest contactRequest)
{
APIResponse<ContactRequest> Response = await _user.SaveMessage(contactRequest);
return StatusCode(Response.Success, Response);
}
and business be like
if (string.IsNullOrEmpty(contactRequest.Name)) Response.Errors.Add("Invalid Name");

if (Response.Errors.Count == 0)
{
Response.Success = (int)StatCode.Success;
Response.Message = "Saved successfully";
}
else
{
Response.Success = (int)StatCode.Bad_Request;
Response.Message = "Error saving name";
}


suggest better ways or let me know if this ones gonna work fine StatCode is an enum for all status code numbers (200,404,401 etc)

8 ответов

21 просмотр

this is good idea i think wait for someone pro that give you correct answer if my answer is wrong.

I use something like this: public class Result<T> { public bool IsSuccess { get; private init; } public T? Value { get; private init; } public string[]? Errors { get; private init; } public static Result<T> Success(T value) => new() { IsSuccess = true, Value = value }; public static Result<T> Failure(string[] errors) => new() { IsSuccess = false, Errors = errors }; } var chat = await _unitOfWork.ChatRepository.FindAsync(x => x.Id == request.ChatId, false); return chat == null ? Result<ChatDto>.Failure([$"Chat with id {request.ChatId} not found"]) : Result<ChatDto>.Success(_mapper.Map(chat));

Jass- Автор вопроса
Іван Карпов
I use something like this: public class Result<T> ...

Glad to see even C# folks start to get into using monads

Jass- Автор вопроса
Jass
is it about c# also going functional thing?

that depends on what will be the outcome if discriminated unions and type unions issues that are being worked on but i have my doubts

Jass
is it about c# also going functional thing?

I don't like it being put in the "functional" thing, but more in the type safety and type-assisted safety

Похожие вопросы

Обсуждают сегодня

А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
62
@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
Чем оно проблема?
Nikita Uzumaki
21
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
Hi, I was reading this https://twitter.com/HouseofChimera/status/1778078991762780408 about Verasity and their likely choice of Tron as blockchain for their token for its low f...
Jordi
13
Заметил в ghci 9.4.8: > :t (<*>) @((->)_) (<*>) @((->)_) :: (w -> (a -> b)) -> (w -> a) -> w -> b Разве не должно (w -> (a -> b)) быть записано как (w -> a -> b)? Это баг, ил...
Михаил
13
@samkazemian - couple questions: Update on frxBTC? - This would do well with the current influx of institutional investment entering the space Update on future veFXS streams...
Costi
16
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Any electron dev here?
Sayanth Tezro
12
Подобного рода ;Следующие три строки это директивы ассемблера, ;которые можно не задавать, т.к.работаем в Visual Studio. ;Символ ";" - это начало однострочного комментария ...
Егор Анелькин
3
Карта сайта