I’m developing a website with Asp.Net core 3.1 and C# version 8.0. I have a class named "ApiResult"
public class ApiResult
{
public bool IsSuccess { get; set; }
public List<string> Message { get; set; } = new List<string>();
public object Data { get; set; }
}
and I’m going to use it on a controller
public async Task<string> CreateBook(BooksCreateEditViewModel ViewModel)
{
if (await _UW.BookRepository.CreateBookAsync(ViewModel))
{
return new ApiResult
{
IsSuccess = true,
Message = new List<string> { "Your job has done" } ,
};
}
else
return "We got an error!!!";
}
But unfortunately, I got a weird error: "Cannot implicity convert ApiResult to the string"
>Solution :
Try changing the return type of your CreateBook method to return Task<ApiResult>. You should then also tweak what you return from your else clause – perhaps set the isSuccess property from your ApiResult model to false. Something along these lines:
public async Task<ApiResult> CreateBook(BooksCreateEditViewModel ViewModel)
{
if (await _UW.BookRepository.CreateBookAsync(ViewModel))
{
return new ApiResult
{
IsSuccess = true,
Message = new List<string> { "Your job has done" } ,
};
}
else
return new ApiResult
{
IsSuccess = false,
Message = new List<string> { "We got an error!!!" } ,
};
}
You could simplify the if statement so that you don’t create the ApiResult object in two different places, this answer is just given as an example.