C# 具有相同名称的属性路由';上传';必须具有相同的模板
我有两个控制器C# 具有相同名称的属性路由';上传';必须具有相同的模板,c#,asp.net-core,C#,Asp.net Core,我有两个控制器 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; u
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;
}
}
}
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Http;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Configuration;
使用阴影数据;
使用shadow.DTO;
使用阴影模型;
使用影子服务;
使用制度;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用系统线程;
使用System.Threading.Tasks;
命名空间shadow.Controllers
{
[路线(“[控制器]”)]
[ApiController]
公共类UserTrustedPersonController:ControllerBase
{
专用IUserService(用户服务);
私人iMail服务(邮递服务),;
专用IConfiguration\u配置;
私有应用程序上下文数据库;
公共静态IWebHostEnvironment\u环境;
public UserTrustedPersonController(IUserService用户服务、iMail服务邮件服务、IConfiguration配置、ApplicationDbContext数据库、IWebHostEnvironment环境)
{
_userService=userService;
_mailService=mailService;
_配置=配置;
_db=db;
_环境=环境;
}
公共类FileUploadAPI
{
公共文件文件{get;set;}
}
[HttpPost]
[路线(“上传2”)]
[过时]
公共异步任务Post(FileUploadAPI objFile)
{
尝试
{
如果(objFile.files.Length>0)
{
如果(!Directory.Exists(_environment.WebRootPath+“\\Upload\\”)
{
目录.CreateDirectory(_environment.WebRootPath+“\\Upload\\”);
}
使用(FileStream FileStream=System.IO.File.Create(_environment.WebRootPath+“\\Upload\\”+objFile.files.files))
{
objFile.files.CopyTo(fileStream);
Flush();
返回“\\Upload\\”+objFile.files.FileName;
}
}
其他的
{
返回“失败”;
}
}
捕获(例外情况除外)
{
返回ex.Message.ToString();
}
}
//上传文件ả新罕布什尔州。
[HttpPost(“上传”,Name=“上传”)]
[产品响应类型(StatusCodes.Status200OK)]
[产品响应类型(typeof(string)、StatusCodes.Status400BadRequest)]
公共异步任务上载文件(IFormFile文件、CancellationToken CancellationToken)
{
如果(检查ExcelFile(文件))
{
等待写入文件(文件);
}
其他的
{
返回BadRequest(新的{message=“无效的文件扩展名”});
}
返回Ok();
}
///
///检查文件是否为excel文件的方法
///
///
///
私有bool CheckIfExcelFile(IFormFile文件)
{
var extension=“.”+file.FileName.Split('..)[file.FileName.Split('..).Length-1];
return(扩展名=“.png”|扩展名=”.jpg“|扩展名=”.bmp“|扩展名=”.gif“|扩展名=”.tif”);//根据需要更改扩展名
}
//专用异步任务写入文件(IFormFile)
专用异步任务写入文件(IFormFile)
{
bool-isSaveSuccess=false;
字符串文件名;
字符串filePath=“”;
尝试
{
var extension=“.”+file.FileName.Split('..)[file.FileName.Split('..).Length-1];
fileName=DateTime.Now.Ticks+extension;//由于安全原因,请为文件创建新名称。
var pathbuild=Path.Combine(Directory.GetCurrentDirectory(),“Upload\\files”);
如果(!Directory.Exists(PathBuild))
{
CreateDirectory(路径构建);
}
var path=path.Combine(Directory.GetCurrentDirectory(),“Upload\\files”,文件名);
filePath=path;
使用(var stream=newfilestream(路径,FileMode.Create))
{
等待文件.CopyToAsync(流);
}
isSaveSuccess=正确;
}
捕获(例外e)
{
//日志错误
}
//回报就是成功;
返回文件路径;
}
}
}
及
使用Microsoft.AspNetCore.Http;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.Extensions.Configuration;
使用阴影数据;
使用阴影模型;
使用影子服务;
使用制度;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用系统线程;
使用System.Threading.Tasks;
命名空间shadow.Controllers
{
[路线(“[控制器]”)]
[ApiController]
公共类ImageFileController:ControllerBase
{
专用IUserService(用户服务);
私人iMail服务(邮递服务),;
专用IConfiguration\u配置;
私有应用程序上下文数据库;
公共ImageFileController(IUserService用户服务、iMail服务邮件服务、IConfiguration配置、ApplicationDbContext上下文/*、SignInManager SignInManager*/)
{
_userService=userService;
_mailService=mailService;
_配置=配置;
_db=上下文;
//_signInManager=signInManager;
}
[HttpPost]
公共异步任务AddImage(ImageFile imageItem)
{
var item=newimagefile
{
//Fullname=trustedPerson.Fullname,
};
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()