ASP.NET Core CreatedAtRoute没有路由与提供的值匹配 [英] ASP.NET Core CreatedAtRoute No route matches the supplied values

查看:292
本文介绍了ASP.NET Core CreatedAtRoute没有路由与提供的值匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Core 2.0.0 Web API尝试构建一个控制器来进行数据库插入。信息可以很好地插入数据库中,但是返回CreatedAtRoute会引发 InvalidOperationException:没有路由与提供的值匹配。到目前为止,我在网上找到的所有内容都表明这是早期ASP预发行版本的错误。 NET Core并已得到修复,但是我不确定该如何处理。以下是我的控制器代码:

Using ASP.NET Core 2.0.0 Web API, I'm trying to build a controller to do a database insert. The information can be inserted into the database just fine, but returning a CreatedAtRoute throws an 'InvalidOperationException: No route matches the supplied values.' Everything I've found online so far says this was a bug with early pre-release versions of ASP.NET Core and has since been fixed, but I'm not really sure what to do about this. The following is my controller code:

[Produces("application/json")]
[Route("api/page")]
public class PageController : Controller
{
    private IPageDataAccess _pageData; // data access layer

    public PageController(IPageDataAccess pageData)
    {
        _pageData = pageData;
    }

    [HttpGet("{id}", Name = "GetPage")]
    public async Task<IActionResult> Get(int id)
    {
        var result = await _pageData.GetPage(id); // data access call

        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] Page page)
    {
        if (page == null)
        {
            return BadRequest();
        }

        await _pageData.CreatePage(page); // data access call

        // Return HTTP 201 response and add a Location header to response
        // TODO - fix this, currently throws exception 'InvalidOperationException: No route matches the supplied values.'
        return CreatedAtRoute("GetPage", new { PageId = page.PageId }, page);
    }

有人能为我提供一些启示吗?

Could anyone possibly shed some light on this for me?

推荐答案

参数需要匹配预期动作的路由值。

The parameters need to match the route values of the intended action.

在这种情况下,您需要 id 而不是 PageId

In this case you need id not PageId

return CreatedAtRoute(
    actionName: "GetPage", 
    routeValues: new { id = page.PageId },
    value: page);

这篇关于ASP.NET Core CreatedAtRoute没有路由与提供的值匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆