当前位置: 首页 > 知识库问答 >
问题:

错误动作的不明确HTTP方法动作需要显式的HttpMethod绑定

喻增
2023-03-14

下面是它在我的控制器中抱怨的“冒犯”代码:

    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)
        {
        }
    }
}

当我测试它时,这个endpoint工作得很好。我设置了路由,它用HTTP修饰,所以我不明白它在抱怨什么。我四处寻找解决方案,但从我所看到的情况来看,它说明控制器中有一个未修饰的公共方法,但该控制器中没有未修饰的方法。这里有什么问题?如果我从HttpGet中删除路由信息,则无法访问该方法,因此我需要同时使用路由和HttpGet修饰器才能访问该方法(除非我也做错了)。我怎么才能修好这个?

共有1个答案

刘瑞
2023-03-14

以下是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。此url适合两种操作:

    null

为每个操作指定唯一的名称和可预测的路由。

而不是拥有这些:

public IActionResult Get() { /*...*/ }
public async Task<IActionResult> Get(int id) { /*...*/ }

重命名一个方法以避免相同的方法名称:

public IActionResult Get() { /*...*/ }
public async Task<IActionResult> GetById(int id) { /*...*/ }
[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) { /*...*/ }
}
 类似资料:
  • 用.NET Core2 API实现SwashBuckle/Swagger我现在在访问Swagger.json时收到500错误:

  • 当我尝试使用Xcode将我的应用程序提交到商店时,我一直遇到这个错误: 错误ITMS-90475:“包无效。iPad多任务支持需要在包'com.companyname.appname'中启动情节提要。” 有人知道这个错误的真正含义吗?

  • 当我尝试使用Xcode向商店提交我的应用程序时,我总是遇到这个错误: 错误ITMS-90475:“包无效。iPad多任务支持需要在包'com.companyname.appname'中启动情节提要。” 有人知道这个错误的真正含义吗?

  • 在Apache Hadoop中使用job.waitForCompletion(true)方法和通过ToolRunner.run(new MyClass(),args)启动map reduce作业有什么区别? 我通过以下两种方式执行MapReduce作业: 首先如下: 其次是: 两种方法的输出都是一样的。但是我不明白这两种方法有什么区别?哪一种比另一种更受欢迎?

  • 问题内容: 我们现在正在学习如何使用多个类,并且有一个项目要求创建一个包含a 和a的类,然后从主类中引用它以找到直径。此代码继续收到错误(标题中提到) 感谢您的帮助,-AJ 更新1 :好的,但是我不必将第三行声明为double,对吗?在我正在学习的书中,该示例没有做到这一点。 如您所见,该代码与我在我的代码中有什么不同?无论出于什么原因,本书的代码中都没有错误,但是我的说法是那里有错误。 问题答案

  • 我正在尝试做一个动画,并使用了下面的代码。我得到了“无法使用类型的参数列表调用'animateWithDuration'”(FloatLiteralConvertible,延迟:FloatLiteralConvertible,选项:UIViewAnimationOptions,animations:()- 这意味着我使用了错误的论点。我可能错了。请帮忙。我真的解决不了。 提前感谢。