我创建了一个.Net Core API(我使用了swagger)。
我创建了一个控制器以上传图片以将其链接到项目。
.cs :
[HttpPut("[Action]/{id}")]
public async Task<ActionResult> Link(int id, IFormFile file)
{
var item = await _context.Item.FirstOrDefaultAsync(t => t.Id == id);
if (item == null)
{
return BadRequest("item null");
}
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
// code to link
return Ok(file);
}
}
我的问题是,如果我想测试它是否有效,我必须使用邮递员,但我想在我的 api 中测试它。
对于Swashbuckle.AspNetCore
with4.0.1
和Swashbuckle.AspNetCore.Swagger
with 4.0.1
,它支持IFormFile
with swagger/index.html
。
详细步骤:
Swashbuckle.AspNetCore
带4.0.1
和Swashbuckle.AspNetCore.Swagger
带4.0.1
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseMvc();
}
}
ApiController
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpPut("[Action]/{id}")]
public async Task<ActionResult> Link(int id, IFormFile file)
{
return Ok(id);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句