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

查看:23
本文介绍了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天全站免登陆