CreatedAtRoute结果为空链接

时间:2018-12-26 10:51:08

标签: asp.net web.api

为什么CreatedAtRoute在CreatedAtRoute对象中产生了正确的201代码,但是在回复邮递员时却显示了500错误代码。

v read most of CreatedAtRoute questions and allready tryed several solutions - but seems that none work for me (or i仍然在做错事。

//Get single method
[Route("{id}")]
    [ProducesResponseType(typeof(WorkerDTO), 200)]
    [ProducesResponseType(typeof(WorkerDTO), 400)]
    public IActionResult GetSingleWorker(int id)
    {
        Worker workerFromRepo = _workerRepository.GetSingle(id);

        if (workerFromRepo == null)
        {
            return NotFound();
        }
        return Ok(Mapper.Map<WorkerDTO>(workerFromRepo));
    }

//Post method
[HttpPost]
    [ProducesResponseType(typeof(WorkerDTO), 201)]
    [ProducesResponseType(typeof(WorkerDTO), 400)]
    public IActionResult AddWorker([FromBody]WorkerCreateDTO workerCreateDTO)
    {
        if (workerCreateDTO == null)
        {
            return BadRequest("Worker Object is null");
        }
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        Worker toAdd = Mapper.Map<Worker>(workerCreateDTO);
        _workerRepository.Add(toAdd);
        bool result = _workerRepository.Save();
        if (!result)
        {
            throw new Exception("Failed to add Worker");
        }
        //returns good 201 code but somewhy fails to link the uri(
        //var tst = CreatedAtRoute("GetSingleWorker" , new { id = toAdd.Id }, Mapper.Map<Worker>(toAdd));
        //return CreatedAtRoute("GetSingleWorker" , new { id = toAdd.Id }, Mapper.Map<Worker>(toAdd));
        return CreatedAtRoute(
            routeName: "GetSingleWorker",
            routeValues: new { id = toAdd.Id },
            value: Mapper.Map<Worker>(toAdd));
    }

结果将获得201和DTO模型。 实际上在tst对象中获得了201代码,但没有得到路由,而在Postman中却出现了500错误。 “处理请求时发生未处理的异常。  InvalidOperationException:没有路由与提供的值匹配。“

1 个答案:

答案 0 :(得分:0)

我是个白痴,对不起。 在asp.net Core中,您似乎需要为路由指定一个名称来引用它,而不是引用方法名称。 因此,将名称属性添加到CreatedAtRoute就可以了。

    [HttpGet]
    [Route("{id}", Name = "GetSingleWorker")]

添加这些内容后-返回好的标头,网址和模型对象:)