要在ASP.NET Core Web API中发送图片和JSON,您可以按照以下步骤进行操作:
ImageController
。using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
namespace YourNamespace.Controllers
{
[ApiController]
[Route("[controller]")]
public class ImageController : ControllerBase
{
private readonly IWebHostEnvironment _environment;
public ImageController(IWebHostEnvironment environment)
{
_environment = environment;
}
[HttpPost]
public async Task UploadImage(IFormFile image)
{
if (image == null || image.Length == 0)
return BadRequest("No image found");
var imagePath = Path.Combine(_environment.ContentRootPath, "Images", image.FileName);
using (var stream = new FileStream(imagePath, FileMode.Create))
{
await image.CopyToAsync(stream);
}
return Ok(new { imagePath });
}
}
}
Startup.cs
文件中的ConfigureServices
方法中添加以下代码以启用文件上传:services.AddControllers();
services.Configure(options =>
{
options.AllowSynchronousIO = true;
});
services.AddDirectoryBrowser();
Startup.cs
文件的Configure
方法中添加以下代码以启用路由:app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Images
来保存上传的图片。现在,您可以使用POST请求发送图像到/image/uploadimage
端点,并且将返回图像的路径。