我正在开发一个 .NET 项目,并尝试使用 Google.Cloud.Storage.V1 NuGet 包集成 Google Cloud Storage。但是,我遇到了无法识别 StorageClient 类的问题,导致 CS0103 错误:“当前上下文中不存在名称‘StorageClient’。”
我已经安装了 Google.Cloud.Storage.V1 软件包,并且将其包含在内。 使用“Google.Cloud.Storage.V1”时,它无法识别Google。 这是代码的相关部分:
图像控制器.cs
using Microsoft.AspNetCore.Mvc;
using Google.Cloud.Storage.V1;
namespace backend.Controllers
{
[ApiController]
[Route("[controller]")]
public class ImagesController : ControllerBase
{
private readonly string _bucketName = "your-bucket-name";
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var storageClient = StorageClient.Create();
var imageObjectName = Guid.NewGuid().ToString();
var imageObjectPath = $"images/{imageObjectName}";
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
memoryStream.Position = 0;
await storageClient.UploadObjectAsync(_bucketName, imageObjectPath, file.ContentType, memoryStream);
}
var imageUrl = $"https://storage.googleapis.com/myproduct-images/{imageObjectPath}";
return Ok(new { Url = imageUrl });
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
}
}
后端.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Cloud.Storage.V1" Version="4.7.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.0" />
</ItemGroup>
</Project>
程序.cs
using backend.Models;
using Microsoft.EntityFrameworkCore;
using Google.Cloud.Storage.V1;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<StorageClient>(provider =>
{
return StorageClient.Create();
});
// Konfigurer DbContext
builder.Services.AddDbContext<UserContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
// Legg til CORS-tjenester
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader());
});
// Legg til andre tjenester
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Konfigurer HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// Bruk CORS-policy
app.UseCors("AllowSpecificOrigin");
app.UseAuthorization();
app.MapControllers();
app.Run();
当我重新启动 Visual Studio code 时它起作用了!