Возвращение свойства модели объекта с дополнительной строкойC#

Место общения программистов C#
Anonymous
Возвращение свойства модели объекта с дополнительной строкой

Сообщение Anonymous »

У меня есть веб-API DotNet Core 8, использующий Dapper в качестве ORM, моя сущность:

Код: Выделить всё

namespace Server.Entities
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Slug { get; set; }
public int CategoryId { get; set; }
public bool Bookmarked = false;
public bool Liked = false;
public bool Premium { get; set; }
public string BriefText { get; set; }
public string Text { get; set; }
public string CoverImage { get; set; }
public int ReadingTime { get; set; }
public Collection Tags = new Collection();
public int Author { get; set; }
public Collection
 Relateds = new Collection();
public Collection Comments = new Collection();
}

public class PostDTO
{
public string Title { get; set; }
public string Slug { get; set; }
public string CoverImage { get; set; }
public string Text { get; set; }
}
}
Мой контроллер:

Код: Выделить всё

 [HttpGet]
public async Task GetAllPosts()
{
PostDTO[] posts = await _dbContext.Post.GetAllAsync();
return Ok(posts);
}
Моя служба:

Код: Выделить всё

 public async Task
 GetAllAsync()
{
string query = "SELECT * FROM Posts";
IEnumerable posts = await _connection.QueryAsync(query);
return posts.ToArray();
}
Как вы видите, я возвращаю PostDTO клиенту, свойство CoverImage — это ImageURL без имени домена, например:

/ uploads/coverImage/2024/7/10/1723272284733-718853888.jpg

чтобы использовать этот URL-адрес впереди, мне нужно указать домен перед URL-адресом, Есть ли способ автоматически объединить домен с объектом перед отправкой его клиенту?
Я использовал это:

Код: Выделить всё

public class PostDTO
{
public string Title { get; set; }
public string Slug { get; set; }

public string CoverImage { get; set; }
public string CoverImageURL
{
get => "http://localhost:8000" + CoverImage;
set => CoverImage = value;
}
public string Text { get; set; }
}
таким образом у меня будет полный URL-адрес изображения, но я думаю, что не стоит возвращать клиенту дополнительные свойства. Что, если я изменю основное свойство: CoverImage, чтобы он возвращал полный URL-адрес? как показано ниже:

Код: Выделить всё

public class PostDTO
{
public string Title { get; set; }
public string Slug { get; set; }

public string CoverImage
{
get => "http://localhost:8000" + CoverImage;
set => CoverImage = value;
}
public string Text { get; set; }
}
при этом я получаю сообщение об ошибке от dapper:

info:
Microsoft.AspNetCore.Mvc. Infrastructure.ControllerActionInvoker[102]
Маршрут соответствует {action = "GetAllPosts", контроллер = "Post"}. Выполнение действия контроллера с подписью
System.Threading.Tasks.Task

Код: Выделить всё

1[Microsoft.AspNetCore.Mvc.ActionResult] GetAllPosts() on controller Server.Controllers.PostController (server). Stack overflow.  Repeat 24234 times: --------------------------------    at Server.Entities.PostDTO.set_CoverImage(System.String) --------------------------------    at DynamicClass.Deserializedeb5d960-6b33-4fce-84f4-e8ee01aaac3a(System.Data.Common.DbDataReader) at Dapper.SqlMapper+d__33
1[[System.__Canon,
System.Private.CoreLib, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]].MoveNext() в
System .Runtime.CompilerServices.AsyncTaskMethodBuilder

Код: Выделить всё

1+AsyncStateMachineBox
1[[System.__Canon,
System.Private.CoreLib, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e],[Dapper.SqlMapper+d__33

Код: Выделить всё

1[[System.__Canon, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Dapper, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]].ExecutionContextCallback(System.Object)    at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)    at System.Runtime.CompilerServices.AsyncTaskMethodBuilder
1+AsyncStateMachineBox

Код: Выделить всё

1[[System.__Canon, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[Dapper.SqlMapper+d__33
1[[System.__Canon,
System.Private.CoreLib, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]], Dapper, Version=2.0.0.0,Culture=neutral,
PublicKeyToken=null]].MoveNext(System.Threading.Thread) в
System.Runtime.CompilerServices.AsyncTaskMethodBuilder

Код: Выделить всё

1+AsyncStateMachineBox
1[[System.__Canon,
System.Private.CoreLib, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e],[Dapper.SqlMapper+d__33

Код: Выделить всё

1[[System.__Canon, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Dapper, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()    at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Runtime.CompilerServices.IAsyncStateMachineBox, Boolean)    at System.Threading.Tasks.Task.RunContinuations(System.Object)    at System.Threading.Tasks.Task.FinishSlow(Boolean)    at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef, System.Threading.Thread)    at System.Threading.Tasks.ThreadPoolTaskScheduler.TryExecuteTaskInline(System.Threading.Tasks.Task, Boolean)    at System.Threading.Tasks.TaskScheduler.TryRunInline(System.Threading.Tasks.Task, Boolean)    at System.Threading.Tasks.TaskContinuation.InlineIfPossibleOrElseQueue(System.Threading.Tasks.Task, Boolean)    at System.Threading.Tasks.ContinueWithTaskContinuation.Run(System.Threading.Tasks.Task, Boolean)    at System.Threading.Tasks.Task.RunContinuations(System.Object)    at System.Threading.Tasks.Task
1[[System.__Canon, System.Private.CoreLib,
Version=8.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]].TrySetResult(System.__Canon) в
System.Threading.Tasks.UnwrapPromise

Код: Выделить всё

1[[System.__Canon, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].TrySetFromTask(System.Threading.Tasks.Task, Boolean)    at System.Threading.Tasks.UnwrapPromise
1[[System.__Canon,
System.Private.CoreLib, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]].ProcessInnerTask(System.Threading.Tasks.Task )
в System.Threading.Tasks.Task.RunContinuations(System.Object) в
System.Threading.Tasks.Task.FinishSlow(Boolean) в
System.Threading.Tasks.Task. ExecuteWithThreadLocal(System.Threading.Tasks.Task
ByRef, System.Threading.Thread) в
System.Threading.ThreadPoolWorkQueue.Dispatch() в
System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart( )


Подробнее здесь: https://stackoverflow.com/questions/790 ... tra-string

Вернуться в «C#»