【发布时间】:2020-09-03 23:04:21
【问题描述】:
我的项目有两个控制器:mvc 和 api。图像已成功从视图传递到 mvc 控制器,问题是如何将其从 mvc 控制器发送到 api 控制器?
[HttpPost]
public IActionResult Create(ProductSubCategoryviewmodel productSubCategory)
{
if (ModelState.IsValid)
{
string uniqueFileName = UploadedFile(productSubCategory);
ProductSubCategoryviewmodel category = new ProductSubCategoryviewmodel();
{
category.ProductSubCategoryName = productSubCategory.ProductSubCategoryName;
category.Rate = productSubCategory.Rate;
category.DisplayOrder = productSubCategory.DisplayOrder;
category.Image = uniqueFileName;
};
}
HttpClient client = api.FromApi();
var prosubjson = JsonConvert.SerializeObject(productSubCategory);
var buffer = Encoding.UTF8.GetBytes(prosubjson);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
try
{
var result = client.PostAsync("api/ProductSubCategories", byteContent).Result;
// TODO: Add insert logic here
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
private string UploadedFile(ProductSubCategoryviewmodel productSubCategory)
{
string uniqueFileName = null;
if (productSubCategory.Image != null)
{
string uploadsFolder = Path.Combine(hostEnvironment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + productSubCategory.Image;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
productSubCategory.Image.CopyTo(fileStream);
}
}
return uniqueFileName;
}
显示错误:没有给出与“string.CopyTo(int, char[], int, int)”所需的形式参数“destination”相对应的参数。强调文本
【问题讨论】:
-
为什么需要将其传递给 API 控制器?如果原因是你想重用 API 控制器中的逻辑,也许你可以创建一个服务层来代替你的 API 和 MVC 控制器使用。
-
感谢您的建议,您能帮我发送示例代码吗?
-
您可以查看我的帖子答案。
标签: asp.net-mvc asp.net-core asp.net-core-webapi