简体   繁体   中英

map route parameter to bool in asp.net web API

So I have registered the following route right now:

configuration.Routes.MapHttpRoute(
            name: "MediaHandler",
            routeTemplate: "api/mediahandler/{action}/{id}",
            defaults: new { controller = "PortalAsset", id = RouteParameter.Optional }
        );

And here is how the controller looks like:

 public class MediaHandlerController : ApiControllerBase
{
    ///...
      [HttpGet]
      [ActionName("download")]
      public async Task<HttpResponseMessage> DownloadAsset(long id)
      {
           // action
      }

I want to add boolean parameter to the controller - isPreview and want to map the routhe the following way:

  1. http://host/api/mediahandler/download/1893 maps to: id =1893, isPreview =false
  2. http://host/api/mediahandler/download/1893/preview maps to: id =1893, isPreview = true

Is there a way I can acomplish that?

With attribute routing you can do like this

[RoutePrefix("api/mediahandler/download")]
public class MediaHandlerController : ApiControllerBase
{
      [HttpGet]
      [Route("{id}")]
      public async Task<HttpResponseMessage> DownloadAsset(long id)
      {
           return DownloadAsset(id, false);
      }

      [HttpGet]
      [Route("{id}/preview")]
      public async Task<HttpResponseMessage> DownloadAssetPreview(long id)
      {
          return DownloadAsset(id, true);
      }

      private async Task<HttpResponseMessage> DownloadAsset(long id, bool isPreview)
      {
           // action
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM