Url.Link始终返回在asp..net web api中使用的null

时间:2017-08-09 18:40:12

标签: c# asp.net-web-api asp.net-web-api-routing

我想为从REST Api返回的DTO创建一些超链接。

变量url始终为空,我不知道为什么?!

为什么网址没有创建,我还缺少什么?

路由的名称是GetStatusFeedback,这是正确的,我还使用Action和Controller作为路由参数+ leadId param!

public class ValuesController : ApiController
{
    [Route("")]
    [HttpGet]
    public IHttpActionResult Get()
    {
        var leadsFromDataBase = new List<Lead> { new Lead { Id = 1 }, new Lead { Id = 2 } };
        var leadDtos = new List<LeadDto>();
        foreach (var lead in leadsFromDataBase)
        {
            var leadDto = new LeadDto();
            string url = Url.Link("GetStatusFeedback", new { LeadId = lead.Id, Action = "Accept", Controller = "values"});
            leadDto.AcceptLink = new Link { Url = url, Verb = "Get" };


            leadDtos.Add(leadDto);
        }
        return Ok(leadDtos);
    }

    [Route("leads/{id:int}/statusfeedback", Name = "GetStatusFeedback")]
    [HttpPost]
    public void Accept(int leadId)
    {

    }

2 个答案:

答案 0 :(得分:4)

路由参数需要与路径模板中的预期参数匹配

string url = Url.Link("GetStatusFeedback", new { id = lead.Id });

应根据"leads/{id:int}/statusfeedback"路线模板

进行匹配

路由模板占位符也需要匹配操作中的参数名称

[Route("leads/{id:int}/statusfeedback", Name = "GetStatusFeedback")]
[HttpPost]
public void Accept(int id) {

}

最后,您应该使用有助于描述路线的正确路线名称。

答案 1 :(得分:0)

花了我一段时间才能从接受的答案中获得所需的信息(我的错误与OP有所不同),这是基于Nkosi的答案和OP的评论的简化版本:

public class ValuesController : ApiController
{
  [HttpGet]
  public IHttpActionResult Get()
  {
    string url = Url.Link("GetStatusFeedback", new { Id = 1, Action = "Accept", Controller = "values"});
    /*or*/ url = Url.Link(nameof(Accept), new { Id = 1,      Action = "Accept", Controller = "values"});
    //not  url = Url.Link(nameof(Accept), new { LeadId = 1,  Action = "Accept", Controller = "values"});

    return Ok(url);
  }

// Controller we want to get the URL of:
[HttpPost("leads/{id:int}/statusfeedback", Name = "GetStatusFeedback")]
public void Accept(int id) //param name matches the line above {id} (in OP it mismatched)
{

}