使用.Net Core 2.2 LinkGenerator的问题

时间:2019-06-26 12:58:10

标签: c# asp.net-core .net-core

在我的控制器中。我正在使用链接生成器将新添加的资源的端点返回给用户。链接生成器始终返回null,我不能完全解释为什么?

我包括了要添加到数据库中的控制器代码。请注意,调用_linkGenerator.GetPathByAction的行-传入的参数是(按顺序)1.操作(在本例中为执行“ Get”的方法的名称),2,控制器名称和3包含正确的ID。老实说,我看不出有问题。

如何定义控制器名称:

namespace CarPriceComparison.Controllers.Api{

[Route("api/vehicles")]
[ApiController]
public class VehicleController : Controller 

“获取”操作-函数头:-

[HttpGet("{vehicleId_:int}")]
public IActionResult GetVehicle(int vehicleId_)
{

执行该操作的“问题”代码。对我来说,传递给_linkGenerator.GetPathByAction的参数看起来很好。关于为什么我总是返回空值的建议?

[HttpPost("")]
public async Task<IActionResult> PostNewVehicleData(VehicleViewModel vehicleData_)
{
    try
    {
        if (ModelState.IsValid)
        {
            var newVehicle = _mapper.Map<Vehicle>(vehicleData_);
            _vehicleRepository.AddVehicle(newVehicle);
            var location = _linkGenerator.GetPathByAction("GetVehicle", "vehicles",
                                                                    new {vehicleId_ = newVehicle.Id});

            if (string.IsNullOrWhiteSpace(location))
            {
                return BadRequest("could not use vehicleId_ to create a new vehicle in the dataase");
            }
            if (await _vehicleRepository.SaveChangesAsync())
            {
                var vehicleModel = _mapper.Map<VehicleViewModel>(newVehicle);

                return Created(location, _mapper.Map<VehicleViewModel>(newVehicle)); 
            }
        } 
        return BadRequest("Failed to save the vehicle");
        }
    catch(Exception ex)
    {
        return BadRequest($"Exception Thrown :  {ex}");
    }
}

1 个答案:

答案 0 :(得分:0)

您必须尝试以下操作:

var location = _linkGenerator.GetPathByAction("GetVehicle", "Vehicle",
                                                                    new {vehicleId_ = newVehicle.Id});

或将您的控制器还给VehiclesController。然后尝试以下方法:

var location = _linkGenerator.GetPathByAction("GetVehicle", "Vehicles",
                                                                    new {vehicleId_ = newVehicle.Id});