ASP.NET Web API CreatedAtRoute return 500 内部服务器错误

ASP.NET Web API CreatedAtRoute return 500 Internal Server Error

我正在尝试构建一个测试网络 API 控制器,只是为了了解网络 API。我写了以下网络 API 控制器:

[Route("api/books")]
public class BookController : Controller
{

    public IEnumerable<Book> Get()
    {
        List<Book> books = new List<Models.Book>();
        books.Add(new Book { Title = "Test Title 1", Author = "Test Author 1", ISBN = "Test ISBN 1" });
        books.Add(new Book { Title = "Test Title 2", Author = "Test Author 2", ISBN = "Test ISBN 2" });

        return books;
    }

    [HttpGet("{id}")]
    public Book Get(int id)
    {
        return new Book { Title = "Test Title 1", Author= "Test Author 1", ISBN="Test ISBN 1", PublishingDate = DateTime.Today.AddYears(-90).AddDays(-73) };
    }


    //[HttpPost]
    //public IActionResult Post([FromBody]Book book)
    //{
    //    string str = "Post request received";

    //    return new JsonResult(str);
    //}


    [HttpPost]
    public IActionResult Post([FromBody]Book book)
    {            
        //return CreatedAtRoute("abi/books", new { controller = "Book", id = 1  }, book);
        //return CreatedAtRoute("Get", new { controller = "Book", id = 1  }, book);
        //return CreatedAtRoute("Get", book);
        //return CreatedAtRoute("abi/books", book);
        return CreatedAtRoute("abi/books/1", book);
    }
}

GetGet(id) 方法工作正常。注释的端口方法也可以正常工作。在另一个 post 方法中,我尝试使用 CreatedAtRoute 方法。当我使用 postman 工具调用此操作时,它 returns 500 internal server error。我为方法参数尝试了几种替代方法(如您在评论 return 语句中看到的那样),但没有一个有效。

这是我得到的详细错误:

System.InvalidOperationException: No route matches the supplied values.

at Microsoft.AspNetCore.Mvc.CreatedAtRouteResult.OnFormatting(ActionContext context)

at Microsoft.AspNetCore.Mvc.Internal.ObjectResultExecutor.ExecuteAsync(ActionContext context, ObjectResult result)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__32.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__31.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__29.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__23.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__18.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.d__6.MoveNext()

非常感谢任何帮助

问题似乎是您的 HTTP POST return 语句中的拼写错误(abi 应该是 api)。修复应该做到这一点。此外,最好为 HTTP GET 方法(即 GetBook)指定路由名称。在您的 HTTP POST return 语句中,传入路由名称以及路由值和对象。此外,您应该先将图书对象包装在 ObjectResult 中,然后再 return HTTP GET 方法中。

// GET /api/books/{id}
[HttpGet("{id}", Name = "GetBook")]
public IActionResult Get(int id)
{
    var book = new Book { 
        Title = "Test Title 1", 
        Author = "Test Author 1", 
        ISBN="Test ISBN 1", 
        PublishingDate = DateTime.Today.AddYears(-90).AddDays(-73) 
    };
    return new ObjectResult(book);
}

// POST api/books
[HttpPost]
public IActionResult Post([FromBody] Book book)
{
    if (book == null)
    {
        return BadRequest();
    }

    // code to add book to database
    //_context.Books.Add(book);
    //_context.Books.SaveChanges();

    return CreatedAtRoute(
        routeName: "GetBook",
        routeValues: new { id = 1 },
        value: book);
}