- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个 Controller
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using shadow.Data;
using shadow.DTO;
using shadow.Models;
using shadow.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace shadow.Controllers
{
[Route("[controller]")]
[ApiController]
public class UserTrustedPersonController : ControllerBase
{
private IUserService _userService;
private IMailService _mailService;
private IConfiguration _configuration;
private ApplicationDbContext _db;
public static IWebHostEnvironment _environment;
public UserTrustedPersonController(IUserService userService, IMailService mailService, IConfiguration configuration, ApplicationDbContext db, IWebHostEnvironment environment)
{
_userService = userService;
_mailService = mailService;
_configuration = configuration;
_db = db;
_environment = environment;
}
public class FileUploadAPI
{
public IFormFile files { get; set; }
}
[HttpPost]
[Route("upload2")]
[Obsolete]
public async Task<string> Post(FileUploadAPI objFile)
{
try
{
if (objFile.files.Length > 0)
{
if (!Directory.Exists(_environment.WebRootPath + "\\Upload\\"))
{
Directory.CreateDirectory(_environment.WebRootPath + "\\Upload\\");
}
using (FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + "\\Upload\\" + objFile.files.FileName))
{
objFile.files.CopyTo(fileStream);
fileStream.Flush();
return "\\Upload\\" + objFile.files.FileName;
}
}
else
{
return "Failed";
}
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
// Upload file ảnh.
[HttpPost("upload", Name = "upload")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UploadFile(IFormFile file, CancellationToken cancellationToken)
{
if (CheckIfExcelFile(file))
{
await WriteFile(file);
}
else
{
return BadRequest(new { message = "Invalid file extension" });
}
return Ok();
}
/// <summary>
/// Method to check if file is excel file
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
private bool CheckIfExcelFile(IFormFile file)
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
return (extension == ".png" || extension == ".jpg" || extension == ".bmp" || extension == ".gif" || extension == ".tif"); // Change the extension based on your need
}
//private async Task<bool> WriteFile(IFormFile file)
private async Task<string> WriteFile(IFormFile file)
{
bool isSaveSuccess = false;
string fileName;
string filePath ="";
try
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.
var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");
if (!Directory.Exists(pathBuilt))
{
Directory.CreateDirectory(pathBuilt);
}
var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files", fileName);
filePath = path;
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
isSaveSuccess = true;
}
catch (Exception e)
{
//log error
}
//return isSaveSuccess;
return filePath;
}
}
}
和
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using shadow.Data;
using shadow.Models;
using shadow.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace shadow.Controllers
{
[Route("[controller]")]
[ApiController]
public class ImageFileController : ControllerBase
{
private IUserService _userService;
private IMailService _mailService;
private IConfiguration _configuration;
private ApplicationDbContext _db;
public ImageFileController(IUserService userService, IMailService mailService, IConfiguration configuration, ApplicationDbContext context /*, SignInManager<IdentityUser> signInManager */)
{
_userService = userService;
_mailService = mailService;
_configuration = configuration;
_db = context;
// _signInManager = signInManager;
}
[HttpPost]
public async Task<ActionResult<ImageFile>> AddImage(ImageFile imageItem)
{
var item = new ImageFile
{
//Fullname = trustedPerson.Fullname,
};
_db.ImageFiles.Add(item);
await _db.SaveChangesAsync();
return item;
}
// Upload file ảnh.
[HttpPost("upload", Name = "upload")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UploadFile(IFormFile file, CancellationToken cancellationToken)
{
if (CheckIfExcelFile(file))
{
await WriteFile(file);
}
else
{
return BadRequest(new { message = "Invalid file extension" });
}
return Ok();
}
/// <summary>
/// Method to check if file is excel file
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
private bool CheckIfExcelFile(IFormFile file)
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
return (extension == ".png" || extension == ".jpg" || extension == ".bmp" || extension == ".gif" || extension == ".tif"); // Change the extension based on your need
}
//private async Task<bool> WriteFile(IFormFile file)
private async Task<string> WriteFile(IFormFile file)
{
bool isSaveSuccess = false;
string fileName;
string filePath = "";
try
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.
var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");
if (!Directory.Exists(pathBuilt))
{
Directory.CreateDirectory(pathBuilt);
}
var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files", fileName);
filePath = path;
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
isSaveSuccess = true;
}
catch (Exception e)
{
//log error
}
//return isSaveSuccess;
return filePath;
}
}
}
错误
System.InvalidOperationException
HResult=0x80131509
Message=The following errors occurred with attribute routing information:
Error 1:
Attribute routes with the same name 'upload' must have the same template:
Action: 'shadow.Controllers.ImageFileController.UploadFile (shadow)' - Template: 'upload'
Action: 'shadow.Controllers.UserTrustedPersonController.UploadFile (shadow)' - Template: 'UserTrustedPerson/upload'
Source=Microsoft.AspNetCore.Mvc.Core
StackTrace:
at Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModelFactory.Flatten[TResult](ApplicationModel application, Func`5 flattener)
at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorBuilder.Build(ApplicationModel application)
at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors()
at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection()
at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize()
at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.GetChangeToken()
at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.<>c__DisplayClass11_0.<Subscribe>b__0()
at Microsoft.Extensions.Primitives.ChangeToken.OnChange(Func`1 changeTokenProducer, Action changeTokenConsumer)
at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.Subscribe()
at Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource..ctor(IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory)
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.GetOrCreateDataSource(IEndpointRouteBuilder endpoints)
at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllers(IEndpointRouteBuilder endpoints)
at shadow.Startup.<>c.<Configure>b__5_0(IEndpointRouteBuilder endpoints) in D:\shadow_backend\Startup.cs:line 120
at Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseEndpoints(IApplicationBuilder builder, Action`1 configure)
at shadow.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in D:\shadow_backend\Startup.cs:line 118
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__31.MoveNext()
最佳答案
在您的代码示例中,您使用以下方式声明您的路线:
[HttpPost("upload", Name = "upload")]
(用户 Controller )[HttpPost("upload", Name = "upload")]
(图像 Controller )
您可以通过以不同方式声明您的路线来解决问题并防止冲突:
✔ [HttpPost, Route([controller]/upload")]
(用户 Controller )
✔ [HttpPost, Route([controller]/upload")]
(图像 Controller )
有用的阅读:
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0#route-name
关于c# - 同名 'upload'的属性路由必须有相同的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63880010/
我写了我遇到的问题,但现在我展示了所有代码xml文件 it can't contain other elements it can contain some other elements
我有两个 Controller using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using
我正在尝试保存几个同名的文件。我想做一些名字做这样的事情:file.extension file[1].extension file[2].extension 我试过这个 http://www.nas
我正在尝试创建一个脚本,该脚本将在多个页面上单击相同名称的按钮,但这些按钮具有不同的属性。有些有 id、一些名称、一些值和一些数据作为标识符。这个函数应该有一个属性列表,当我运行脚本时,它应该进入该列
从 Oracle 迁移我想重用一些定义,例如: ALTER TABLE CLIENTUSERS ADD CONSTRAINT UK_CLIENTUSERS_CLIENTUS UNIQUE (CLIEN
我有一个关于 unix 命令行的问题。我有很多这样的文件: /f/f1/file.txt /f/f2/file.txt /f/f3/file.txt and so on. 我想将所有 file.txt
我在表单“delsel2”中有几个复选框(全部具有相同的名称),如下所示: 我希望能够在选择其中任何一个时简单地发出警报,并显示一条消息指示是否选中其中任何一个。 我已经想出了这个,但它不起作用
假设您在子目录 project_1, ..., project_10 中有 10 个项目,它们都在父目录 projects 中。 所有项目都使用相同的库,在 project/project_n/lib
我有一个生成 iOS 框架的 Xcode 项目。我有两个版本的二进制文件要生成 - 一个供内部使用,没有许可要求,另一个供外部使用,但有许可要求。 我想我会为此制定两个目标,并使用不同的 swift
我已经读过有关 jQuery 验证的内容,但我仍然坚持在表单中需要控制数组。 我有这个代码: //already link the validation js script of course
我对这个领域很陌生。我正在尝试阅读一个示例程序。 第一个是team.c #include "support.h" struct team_t team = { "", /* first membe
我有一个包含一组复选框的 HTML 表单: Apple Banana Strawberry 当我单击一个按钮时,我希望将所有选中的同名复选框放在一个数组中。 因此,如果用户选择 Apple 和
我将第一个表存储在数据库中,如图所示,我必须对其应用查询以像第二个表一样显示它 最佳答案 这是使用条件聚合的一个选项: select subject, max(case when exa
对于我文件夹中的每个 mp3 文件,我都有一个同名的 jpg 文件,我试图用 cmd 实现的是将该名称变成一个没有文件扩展名的变量名 这是我只使用 mp3 名称的代码 for %%a in ("*.m
我有 2 个数据库....a 和 b 我在这两个数据库中都有表“t”。 现在我正在从数据库“b”中删除表 t。 我创建了一个 View “t”(请参阅 View 名称与已删除的表相同) 数据库“b
我正在创建一个有特定问题的 SCSS 网格 - 我想使用一个变量名,例如 $pad(用于填充值),但是 $pad变量在不同的媒体断点中需要不同。 首先通过动态创建断点并在其中设置 $pad 值的 mi
一些背景知识: 我正在尝试将我在 Solaris 上运行的一些 .ksh 文件移植到使用 Cygwin 的 Windows 上运行。在 Solaris 机器上运行的 ksh 实现与可在处理子 shel
当执行 tar 提取操作时,有时内容会直接提取到父文件夹,这很糟糕,因为它们变得杂乱无章。例如: tar -xzf foo1.tar.gz 摘录: ./file1 ./file2 ./file3 解决
我想做这样的事情: class X: @classmethod def id(cls): return cls.__name__ def id(self):
我正在看 John De Goes “FP to the Max”视频。在代码中,他做了这样的事情来获取隐式对象: object Program { def apply[F[_]](imp
我是一名优秀的程序员,十分优秀!