Home > Software design >  Route("save-file-to-physicallocation") - Routing parameter in asp.net
Route("save-file-to-physicallocation") - Routing parameter in asp.net

Time:08-16

There was this sample code which had the following routing param defined as

    [HttpPost]
    [Route("save-file-to-physicallocation")]
    public async Task<IActionResult> SaveToPhysicalLocation([FromBody] SaveFile saveFile)
    {
        foreach (var file in saveFile.Files)
        {
            string fileExtenstion = file.FileType.ToLower().Contains("png") ? "png" : "jpg";
            string fileName = $@"D:\MyTest\{Guid.NewGuid()}.{fileExtenstion}";
            using (var fileStream = System.IO.File.Create(fileName))
            {
                await fileStream.WriteAsync(file.ImageBytes);
            }
        }
        return Ok();
    }

What does this mean?

I know routing param with respect to controller.

[ApiController]
[Route("api/firewall")]

which means http://someurl/api/firewall

what does this mean?

[Route("save-file-to-physicallocation")]

CodePudding user response:

In ASP.NET MVC Controller you can specify routing using Route() attribute. It accepts a string that specify the part of URL used to access that Controller or action.

In case you have Route() specified on Controller then actions accessed using that route and action method. Sometimes, you might need different route for specific action in addition to Controller route. Cases like having two actions with GET method then you need to add another segment to one of those actions to identify it from the other.

Let's take the following routing on your Controller class:

[ApiController]
[Route("api/firewall")]

This route on action method in that class:

[Route("save-file-to-physicallocation")]

Then to access that route you should send request to api/firewall/save-file-to-physicallocation to hit that action.

BTW you can do the same by adding to action route to the HTTP method attribute:

[HttpPost("save-file-to-physicallocation")]

That will basically provide the same functionality but with less used attributes.

  • Related