繁体   English   中英

如何在asp.net核心api控制器中将url中的字符串作为参数传递

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

我正在尝试构建一个从主体获取IForm文件的api,然后保存该文件。 然后在响应中返回文件名。 我以前也取得了相同的成绩。 但是然后我有一个整数值作为参数,在这种情况下,它是一个字符串。 我正在尝试这种方式。 但是,当路由匹配时,它始终返回状态200,而不在响应中保存文件和文件名。

[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);
}

尽管响应为200。当它应该是无效的文件类型时,它甚至没有显示任何错误请求。

看起来您似乎已经明白了,但是只是要回答这个问题,您需要删除$然后可以使用[FromRoute]属性指定email参数来自路由,但可能不是必需的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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