【发布时间】:2018-08-31 21:35:47
【问题描述】:
我正在尝试从我的控制器添加Article。但它不起作用。当我使用邮递员时,我收到错误 500
ServiceFilter(typeof(LogUserActivity))]
[Route("api/users/{userId}/[controller]")]
[ApiController]
public class ArticleController : ControllerBase
{
private readonly IPrmRepository _repo;
private readonly IMapper _mapper;
public ArticleController(IPrmRepository repo, IMapper mapper)
{
_mapper = mapper;
_repo = repo;
}
public async Task<IActionResult> CretaArticle(int userId, ArticleForCreation articleForCreation)
{
var author = await _repo.GetUser(userId, false);
//check autorization
if (author.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();
articleForCreation.AuthorId = userId;
var article = _mapper.Map<Article>(articleForCreation);
_repo.Add(article);
if (await _repo.SaveAll())
{
//Mapp Data to return db
var articleToReturn = _mapper.Map<ArticleToReturnDto>(article);
return CreatedAtRoute("GetArticle", new {id = article.ArticleId}, articleToReturn);
}
throw new Exception("Creating the article failed on save");
}
负责数据库中模型的模型:
public class Article
{
public int ArticleId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int AuthorId{get; set;}
public User Author { get; set; }
}
Dtos:
public class ArticleForCreation
{
public int AuthorId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class ArticleToReturnDto
{
public int Id { get; set; }
public int AuthorId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
AutomapperProfile 将数据映射到数据库:
CreateMap<ArticleForCreation, Article>().ReverseMap();
CreateMap<Article, ArticleToReturnDto>();
有人可以帮助您了解为什么它不起作用吗?
【问题讨论】:
-
欢迎来到stackoverflow!是抛出异常还是看到某种错误消息?
-
请提供有关您收到的错误的更多详细信息。
-
可能只是在您的操作
CretaArticle上添加一个“[HttpPost]”。您能提供如何将数据发布到服务器吗?
标签: c# asp.net asp.net-core .net-core