CreatedAtRoute routing to different controller

前端 未结 3 1941
闹比i
闹比i 2020-12-13 12:33

I\'m creating a new webapi using attribute routing to create a nested route as so:

    // PUT: api/Channels/5/Messages
    [ResponseType(typeof(void))]
    [         


        
3条回答
  •  鱼传尺愫
    2020-12-13 13:18

    Late to the party but an alternative answer. If the action you are routing to also uses attribute routing, you can give the route a name and pass that in to the CreatedAtRoute method. This is done by setting a Name property on the Route. Following your post example, consider the following action.

    // GET: api/Messages/5
    [Route("api/messages/{id}", Name="GetMessage")]
    public async Task GetMessage(int id)
    {
        // get the message
    }
    

    Note that the Name property on the route attribute, [Route("api/messages/{id}", Name="GetMessage")], is set to "GetMessage". By doing this we can call the CreatedAtRoute method from the PostChannelMessage action and pass in the route name like so:

    return CreatedAtRoute("GetMessage", new { id = message.Id }, message);
    

    This is a scenario I encountered and my searching led here so thought I would post this alternative answer in case it helps anyone else.

提交回复
热议问题