How to pass string in the url as a parameter in asp.net core api controller

Viewed 10220

I am trying to build an api that takes an IForm file from the body and then save the file. Then return the filename in the response. I achieved the same before. But then I had an integer value as the parameter, this case it is a string. I am trying this way. But when the route matches it always returning status 200 without saving the file and filename in the response.

[HttpPost]
[Route("/api/users/${email}/photos")]
public async Task<IActionResult> Upload(string email, [FromBody]IFormFile fileStream)
{
    var user = this.repository.GetUserByEmail(email);
    if (user == null)
        return NotFound();
    var uploadsFolderPath = Path.Combine(host.WebRootPath, "Images");
    if (!Directory.Exists(uploadsFolderPath))
        Directory.CreateDirectory(uploadsFolderPath);

    if (fileStream == null) return BadRequest("null file");
    if (fileStream.Length == 0) return BadRequest("Empty file");
    if (fileStream.Length >= photoSettings.MaxBytes) return BadRequest("Max file size exceeded");
    if (!photoSettings.IsSupported(fileStream.FileName)) return BadRequest("Invalid file type");

    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName);
    var filePath = Path.Combine(uploadsFolderPath, fileName);
    using (var stream = new FileStream(filePath, FileMode.Create))
    {
        await fileStream.CopyToAsync(stream);
    }
    user.ImageUrl = fileName;
    await unitOfWork.CompleteAsync();
    return Ok(fileName);
}

Though the response is 200. it is not even showing any bad request when it should be invalid filetype.

1 Answers

It looks like you figured it out, but just to answer the question you need to remove the $ and you can specify that the email parameter is from the route using the attribute [FromRoute] but it may not be required.

[HttpPost]
[Route("/api/users/{email}/photos")]
public async Task<IActionResult> Upload([FromRoute]string email, [FromBody]IFormFile fileStream)
{
    //..
}
Related