我正在为个人项目实现OData。这时我有了这段代码
[HttpPost]
[ODataRoute("Classes", RouteName = "PostClass")]
public IActionResult PostClass([FromBody] Class @class)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
@class.Id = Guid.NewGuid();
_context.Classes.Add(@class);
_context.SaveChangesAsync();
//return CreatedAtAction("GetClass", new { id = @class.Id }, @class);
return Created(@class);
}
它工作正常,但是我想如果可以使用sync await系统来改善它,如下所示:
[HttpPost]
[ODataRoute("Classes", RouteName = "PostClass")]
public async Task<ActionResult<Class>> PostClass([FromBody] Class @class)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
@class.Id = Guid.NewGuid();
_context.Classes.Add(@class);
await _context.SaveChangesAsync();
return CreatedAtAction("GetClass", new { id = @class.Id }, @class);
//return Created(@class);
}
当我执行第二种解决方案时,代码会生成,但是出现500 Internal Server Error。
使用
[HttpPost]
[ODataRoute("Classes", RouteName = "PostClass")]
public async Task<ActionResult<Class>> PostClass([FromBody] Class @class)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
@class.Id = Guid.NewGuid();
_context.Classes.Add(@class);
await _context.SaveChangesAsync();
//return CreatedAtAction("GetClass", new { id = @class.Id }, @class);
return Created(@class);
}
由于
而无法构建代码严重性代码描述项目文件行抑制状态 错误CS0029无法隐式转换类型 'Microsoft.AspNet.OData.Results.CreatedODataResult' 至 'Microsoft.AspNetCore.Mvc.ActionResult'Oyg.Api C:\ Users \ Public \ Projects \ oyg-server \ Api \ Controllers \ ClassesController.cs 96活动
好的,但是那我应该用什么方法代替Created()?
答案 0 :(得分:0)
这是因为CreatedODataResult返回的Created<TEntity>(entity)
method类型不是ActionResult的子类,而是implements the IActionResult
interface的类:
public class CreatedODataResult<T> : IActionResult
{
// ...
}
要修复代码,只需将Task<ActionResult<Class>>
更改为Task<IActionResult>
即可:
[HttpPost]
[ODataRoute("Classes", RouteName = "PostClass")]
public async Task<IActionResult> PostClass([FromBody] Class @class)
{
// ...
return Created(@class);
}