MVC APIController With CustomNames

Viewed 55

So im new to netcoreapp and im trying to convert my old rest api to the new one.

The problem is that im having trouble to use custom methods name and parameters.

I only want to have [HttpGet] or [HttpPost] and then the action and the parameter.

So for example

[HttpGet]
public List<string> GetStrings(string firstString, string lastString){
 // my code here
}

and then i try calling this, which is not working at all

baseUrl/controller/GetStrings?firstString=test&lastString=test2

See my controller below to understand my problem

[ApiController]
[Route("api/[controller]")]
public class YoutubeController : ControllerBase, IYoutubeController
{
    [HttpPost]
    public async Task<YoutubeVideoInfo> GetVideoAsync(string videoId)
    {
        // my code
    }

    [HttpGet]
    public List<YoutubeItem> Playlist([FromQuery]string playlistId)
    {
        // My code
    }

    [HttpGet]
    public YoutubeVideoCollection Search(string searchString, int pageSize = 50, string relatedTo = null, VideoSearchType videoSearchType = VideoSearchType.Videos)
    {
     // my code
    }
}

}

I tried Calling Search like this, without any luck

https://localhost:44330/Youtube.Manager.Core.API/api/Youtube/Search?searchString=Eminem&pageSize=20&relatedTo=&videoSearchType=Videos

And this is my routing config

  app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "api/{controller=Home}/{action=Index}/{id?}"
                );
        });

Is there any other configration i need to have, and also please i do not want to have too specify anything in my [HttpGet] Attribute.

In net framework i hade WebApiConfig which it could handle those kind of operation. Is there nothing like it in netcoreapp?

2 Answers

Decorate your controller like this:

[ApiController]
[RoutePrefix("api/[controller]")]
public class YoutubeController : ControllerBase, IYoutubeController
{
    [HttpPost, Route("GetVideoAsync")]
    public async Task<YoutubeVideoInfo> GetVideoAsync(string videoId)
    {
        // my code
    }

    [HttpGet, Route("Playlist")]
    public List<YoutubeItem> Playlist([FromQuery]string playlistId)
    {
        // My code
    }

    [HttpGet, Route("Search/{searchString}/{pageSize}/{relatedTo}/{videoSearchType}")]
    public YoutubeVideoCollection Search(string searchString, int pageSize = 50, string relatedTo = null, VideoSearchType videoSearchType = VideoSearchType.Videos)
    {
     // my code
    }
}

And add the following line in your RouteConfig:

routes.MapMvcAttributeRoutes();

To get the action name to be part of the route, you need to update the [Route(..)] attribute to take the action into account. You're already using the [controller] token in your example, so just add [action]:

[Route("api/[controller]/[action]")]

See the docs for a detailed explanation of token replacement.

Related