gpt4 book ai didi

.net - Swagger 错误 用于操作的模糊 HTTP 方法 操作需要显式 HttpMethod 绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 01:18:31 34 4
gpt4 key购买 nike

我正在尝试为我的 API 生成 swagger 文档。每次我导航到 Swagger 文档时,我都会收到此错误:

Ambiguous HTTP method for action - [ControllerName]Controller.DownloadFile. Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0


这是它在我的 Controller 中提示的“违规”代码:
    using Models;
using Utilities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;


namespace Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LibrarianController : ControllerBase
{
private IFileUploadUtilties fileUtilities;
private IConfiguration config;
private ApiContext context;
private IFileRetrieval fileRetrieval;
public LibrarianController(IFileUploadUtilties utilities, IConfiguration config, FinwiseApiContext context, IFileRetrieval fileRetrieval)
{
fileUtilities = utilities;
this.config = config;
this.context = context;
this.fileRetrieval = fileRetrieval;
}

[HttpGet]
public IActionResult Get()
{
return Ok("Ok");
}

// GET api/<LibrarianController>/5
[HttpGet("/api/[controller]/{Id}")]
public async Task<IActionResult> Get(int id)
{
try
{
return Ok(await fileRetrieval.GetFileForPartnerItemById(id));
}
catch(Exception ex)
{
return NotFound();
}

}
[HttpGet ("/api/[controller]/[action]/{fileId}")]
public async Task<IActionResult> DownloadFile(int fileId)
{
if (fileId == 0)
return Content("File Id missing");

var fileDownload = await fileRetrieval.GetFileForPartnerItemById(fileId);
var contentType = await fileUtilities.GetFileType(Path.GetExtension(fileDownload.NewFileName));

var path = Path.Combine(config.GetSection("StoredFilePath").Value, fileDownload.NewFileName);

var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, contentType, Path.GetFileName(path));
}

[HttpGet("api/[controller]/{PartnerId}/{ItemId}")]
public async Task<List<FileUploads>> GetFiles(string PartnerId, string ItemId)
{
var getFiles = await fileRetrieval.GetAllFilesForPartnerItem(PartnerId, ItemId);
return getFiles;
}


// POST api/<LibrarianController>
[HttpPost]
public async Task<IActionResult> Post([FromForm] FileInformation fileInfo)
{
int newFileVersion = 1;

if (fileInfo == null || fileInfo.Files == null || fileInfo.Files.Count == 0)
return BadRequest("File(s) not found");

try
{
foreach (var locFile in fileInfo.Files)
{
//check for file extension, if not there, return an error
var fileExtension = Path.GetExtension(locFile.FileName);
if (string.IsNullOrEmpty(fileExtension))
return BadRequest("Files must include file extension");


var valid = await fileUtilities.IsFileValid(locFile);

var newFileName = string.Concat(Guid.NewGuid().ToString(),valid.fileExtension);

var newFileLocation = Path.Combine(config.GetSection("StoredFilePath").Value, newFileName);


if (!valid.FileExtensionFound)
{
return BadRequest($"Error {valid.FileExtensionFoundError}");
}
if (!valid.FileSizeAllowed)
{
return BadRequest($"Error: {valid.FileSizeAllowedError}");
}


//check for an existing file in the database. If there is one, increment the file version before the save
var currentFile = await fileUtilities.FileExists(fileInfo, locFile);

if (currentFile != null)
{
newFileVersion = currentFile.Version + 1;
}

//save to the file system
using (var stream = new FileStream(newFileLocation, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
await locFile.CopyToAsync(stream);
}

//save to the db. Check to see if the file exists first. If it does, do an insert, if not, return an error
if (System.IO.File.Exists(newFileLocation))
{
FileUploads upload = new FileUploads
{
EntityId = fileInfo.EntityId,
FileName = locFile.FileName,
ItemId = fileInfo.ItemId.ToString(),
NewFileName = newFileName,
ValidFile = true,
Version = newFileVersion
};
context.FileUploads.Add(upload);
context.SaveChanges();
//TODO: fire event the file has been saved provide Id key to find the record
//upload.Id;
}
else
{
return BadRequest("Error: File Could not be saved");
}

}
}
catch (Exception ex)
{
return BadRequest("Failure to upload files.");
}
return Ok("File Uploaded");
}

// PUT api/<LibrarianController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/<LibrarianController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
当我测试它时,这个端点工作正常。我设置了路由,它用 HTTP 装饰,所以我不明白它在提示什么。我环顾四周寻找解决方案,但据我所知,它表明 Controller 中没有修饰的公共(public)方法,但是该 Controller 中没有未修饰的方法。这里有什么问题?如果我从 HttpGet 中删除路由信息,则无法访问该方法,因此我需要同时拥有 Route 和 HttpGet 装饰器才能访问此方法(除非我也做错了)。我怎样才能解决这个问题?

最佳答案

为什么模棱两可
这是您前往 DownloadFile() 的路线:

[HttpGet ("/api/[controller]/[action]/{fileId}")]
public async Task<IActionResult> DownloadFile(int fileId)
这是 GetFiles() :
[HttpGet("api/[controller]/{PartnerId}/{ItemId}")]
public async Task<List<FileUploads>> GetFiles(string PartnerId, string ItemId)
考虑一个 GET 请求 /api/Librarian/DownloadFile/62959061 .此网址适合两种操作:
  • 对于 DownloadFile() , 下载文件为 [action]和 62959061 是 fileId .
  • 对于 GetFiles() , 下载文件为 PartnerId和 62959061 是 ItemId . (在进行模型绑定(bind)时,.NET 会将 62959061 视为字符串。)

  • 这就是为什么你有模棱两可的错误。
    建议
    为每个操作分配一个唯一的名称和可预测的路线。
    1.方法名重复
    而不是这些:
    public IActionResult Get() { /*...*/ }
    public async Task<IActionResult> Get(int id) { /*...*/ }
    重命名方法之一以避免相同的方法名称:
    public IActionResult Get() { /*...*/ }
    public async Task<IActionResult> GetById(int id) { /*...*/ }
    2. 定义独特的路线
    形成你定义的 Controller ,我建议你使用 [RoutePrefix]在 Controller 级别并使用 [Route][Http{Method}]在行动层面。 Here是关于它们是什么的相关讨论。
    使用相同的模式定义路由可以避免意外创建模糊路由。以下是我重新定义路由的尝试:
    [RoutePrefix("api/[controller]")] // api/Librarian
    [ApiController]
    public class LibrarianController : ControllerBase
    {
    [HttpGet("")] // GET api/Librarian/
    public IActionResult Get() { /*...*/ }

    [HttpGet("{Id}")] // GET api/Librarian/62959061
    public async Task<IActionResult> GetById(int id) { /*...*/ }

    [HttpGet("download/{fileId}")] // GET api/Librarian/download/62959061
    public async Task<IActionResult> DownloadFile(int fileId) { /*...*/ }

    [HttpGet("getfiles/{PartnerId}/{ItemId}")] // GET api/Librarian/getfiles/partnerid/itemid
    public async Task<List<FileUploads>> GetFiles(string PartnerId, string ItemId) { /*...*/ }

    [HttpPost("")] // POST api/Librarian/
    public async Task<IActionResult> Post([FromForm] FileInformation fileInfo) { /*...*/ }

    [HttpPut("{id}")] // PUT api/Librarian/62959061
    public void Put(int id, [FromBody] string value) { /*...*/ }

    [HttpDelete("{id}")] // DELETE api/Librarian/62959061
    public void Delete(int id) { /*...*/ }
    }
    通过为 DownloadFile() 添加路径和 GetFiles()应用程序应该能够正确识别路线,因为应用程序知道 /download 的所有路线必去 DownloadFile()以及带有 /getfiles 的所有路线必去 GetFiles() .

    关于.net - Swagger 错误 用于操作的模糊 HTTP 方法 操作需要显式 HttpMethod 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62959061/

    34 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com