【发布时间】:2018-11-12 04:12:29
【问题描述】:
我是 .Net Core 开发的新手。我有一个模型:
public class CoreGoal
{
[Key]
public long CoreGoalId { get; set; }
public string Title { get; set; }
public string Effect { get; set; }
public string Target_Audience { get; set; }
public string Infrastructure { get; set; }
public virtual ICollection<Image> Images { get; set; }
public CoreGoal()
{
}
}
图像模型如下:
public class Image
{
[Key]
public long ImagelId { get; set; }
public string Base64 { get; set; }
[ForeignKey("CoreGoalId")]
public long CoreGoalId { get; set; }
public Image()
{
}
}
我正在使用存储库模式。我的仓库:
public interface ICoreGoalRepository
{
void CreateCoreGoal(CoreGoal coreGoal);
}
public class CoreGoalRepository : ICoreGoalRepository
{
private readonly WebAPIDataContext _db;
public CoreGoalRepository(WebAPIDataContext db)
{
_db = db;
}
//Find specific
public CoreGoal Find(long key)
{
return _db.CoreGoals.FirstOrDefault(t => t.CoreGoalId == key);
}
//Add new
public void CreateCoreGoal(CoreGoal coreGoal)
{
_db.CoreGoals.Add(coreGoal);
_db.SaveChanges();
}
}
和控制器:
[Route("api/[controller]")]
public class CoreGoalController : Controller
{
private readonly ICoreGoalRepository _coreGoalRepository;
//Controller
public CoreGoalController(ICoreGoalRepository coreGoalRepository) {
_coreGoalRepository = coreGoalRepository;
}
[HttpGet("{id}", Name = "GetCoreGoal")]
public IActionResult GetById(long id)
{
var item = _coreGoalRepository.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
//Create
[HttpPost]
public IActionResult Create([FromBody] CoreGoal item)
{
if (item == null)
{
return BadRequest();
}
_coreGoalRepository.CreateCoreGoal(item);
return CreatedAtRoute("GetCoreGoal", new { id = item.CoreGoalId }, item);
}
}
在 CoreGoal 的 POST 请求中 - 创建新的 CoreGoal 时,我想将图像模型的 Base64 属性从字符串转换为字节 []。我找到了这个 (https://adrientorris.github.io/aspnet-core/manage-base64-encoding.html) 博客文章,但我不确定我应该在哪里编写这段代码。
有人可以帮助我吗?
【问题讨论】:
-
这个问题对我来说不是很清楚,请您提供更多详细信息吗?
-
所以,基本上 My CoreGoal 可以有很多图像,这就是为什么我将它创建为一个单独的模型。现在,Image 模型有一个属性 Base64,其类型为字符串。当我创建一个 CoreGoal 时,我还发布了 base64 字符串,不幸的是,在保存到我的 MySql 数据库时,这个大字符串被截断了一半。所以有人建议我不要使用字符串,而是使用 byte[] 作为数据类型。但是,如果我将其更改为 byte[],我的 POST 请求将失败,状态为 400。因此,也许不是将其更改为 byte[] 编码可以工作。 stackoverflow.com/questions/43248760/…
标签: asp.net-core asp.net-core-webapi