Dan*_* R. 5 c# asp.net-core-2.0
我正在使用 IActionResult(任务)上传文件,并在我的控制器中引用该文件。我想取回的是文件名。
控制器 ->
var imageLocation = await _imageHandler.UploadImage(image);
Run Code Online (Sandbox Code Playgroud)
ImageHandler ->
public async Task<IActionResult> UploadImage(IFormFile file)
{
var result = await _imageWriter.UploadImage(file);
return new ObjectResult(result);
}
Run Code Online (Sandbox Code Playgroud)
我的值存储在 imageLocation 中,但我不知道如何访问它(我需要“值”字符串以便我可以将它添加到数据库中)。
我尝试过搜索所有内容,但每个人都在使用列表。我这里只需要一个字符串。希望大家能帮帮我。谢谢!
您可以将结果转换为所需的类型并调用属性
控制器
var imageLocation = await _imageHandler.UploadImage(image);
var objectResult = imageLocation as ObjectResult;
var value = objectReult.Value;
Run Code Online (Sandbox Code Playgroud)
或者只是重构ImageHandler.UploadImage
函数以返回实际类型以避免必须强制转换
public async Task<ObjectResult> UploadImage(IFormFile file) {
var result = await _imageWriter.UploadImage(file);
return new ObjectResult(result);
}
Run Code Online (Sandbox Code Playgroud)
并在控制器中获得预期的值
var imageLocation = await _imageHandler.UploadImage(image);
var value = imageLocation.Value;
Run Code Online (Sandbox Code Playgroud)
更好的是,让函数只返回所需的值
public Task<string> UploadImage(IFormFile file) {
return _imageWriter.UploadImage(file);
}
Run Code Online (Sandbox Code Playgroud)
这样你就可以在控制器中调用函数时得到预期的结果。
string imageLocation = await _imageHandler.UploadImage(image);
Run Code Online (Sandbox Code Playgroud)