简体   繁体   English

为什么在上传处理时我的 ASP.NET Core 7 MVC 中出现 FileNotFOund 异常?

[英]Why am I getting a FileNotFOund Exception in my ASP.NET Core 7 MVC while upload handling?

I have this model:我有这个 model:

public class ContactFormModel
{        
    [Required]
    [EmailAddress]
    public string Email { get; set; } = string.Empty;
    
    [StringLength(4096, ErrorMessage = "Your message is too long. Please shorten it to max. 4096 chars.")]
    [MinLength(5)]
    [Required]
    public string Body { get; set; } = string.Empty;
    
    [Required]
    [StringLength(100, ErrorMessage = "Name is too long. Just 100 chars allowed.")]
    public string Name { get; set; } = string.Empty;
    
    [Required]
    [StringLength(150, ErrorMessage = "Subject too long. Just 150 chars allowed.")]
    public string Subject { get; set; } = string.Empty;
            
    public IList<IFormFile>? Attachment { get; set; }
}

My contact form sends the data to my Controller:我的联系表将数据发送到我的 Controller:

[HttpPost("contact")]
[ValidateAntiForgeryToken]        
public async Task<IActionResult> Contact(ContactFormModel model)
{
    try
    {
        if (ModelState.IsValid)
        {
            var spamState = VerifyNoSpam(model);

            if (!spamState.Success)
            {
                return BadRequest(new { Reason = spamState.Reason });
            }

            if (model?.Attachment?.Count > 0)
            {
                await _mailService.SendMailAsync("ContactTemplate.txt", model.Name, model.Email, model.Subject, model.Body, model.Attachment);
            }
            else
            {
                await _mailService.SendMailAsync("ContactTemplate.txt", model.Name, model.Email, model.Subject, model.Body);
            }

            _logger.LogDebug("Sent email.");

            return View("EmailSent");
        }
        else
        {
            return BadRequest(new { Reason = "It looks like one or more information you entered was not valid." });
        }
    }
    catch (Exception ex)
    {
        _logger.LogError("Failed to send email from contact page", ex);
        return BadRequest(new { Reason = "Error Occurred" });
    }
}

Currently the controller holds the full model with one attachment.目前 controller 拥有完整的 model 和一个附件。 I have a known filename and all other information about the file.我有一个已知的文件名和有关该文件的所有其他信息。 Now i give that information to my Emailservice :现在我将该信息提供给我的Emailservice

public async Task<bool> SendMailAsync(string template, string name, string email, string subject, string msg, [Optional] IList<IFormFile> attachment)
{
        try
        {
            ...
            if (attachment != null)
            {
                this.logger.LogInformation("Attempting to send mail via SendGrid with attachment");
                foreach (var attachmentItem in attachment)
                {
                    string fileName = Path.GetFileName(attachmentItem.FileName);
      Exception --> byte[] byteData = Encoding.ASCII.GetBytes(File.ReadAllText(fileName));
                    mailMsg.Attachments = new List<Attachment>
                    {
                        new Attachment
                        {
                            Content = Convert.ToBase64String(byteData),
                            Filename = fileName,
                            Disposition = "attachment",
                        },
                    };
                }
            }
        }
}

Now I'm getting a "FileNotFound" exception because it looks in src\MannsBlog\22060_CODE_1-2023_Web.pdf my application directory.现在我收到一个“FileNotFound”异常,因为它在我的应用程序目录src\MannsBlog\22060_CODE_1-2023_Web.pdf中查找。

But in general I'm expecting, that it searches in my download dir (where I browsed to).但总的来说,我期望它会在我的下载目录(我浏览的位置)中搜索。

How can I fix this?我怎样才能解决这个问题?

just because File.ReadAllText() requires the path,if you just pass the name of the file to the method,it would combine your current Directory with the name to construct a new absolute path只是因为File.ReadAllText()需要路径,如果你只是将文件的名称传递给方法,它会将你当前的目录与名称结合起来构造一个新的绝对路径

You could get the fielstream with IFormFile.OpenReadStream() method and get the base64string as below:您可以使用IFormFile.OpenReadStream()方法获取 fielstream 并获取 base64string,如下所示:

var fs=file.OpenReadStream();
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
fs.Close();
var base64str=Convert.ToBase64String(bt);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试创建ASP.NET MVC 4控制器时出现FileNotFound异常 - FileNotFound exception while trying to create ASP.NET MVC 4 controller 我收到空异常错误 ASP.NET MVC - I am getting Null exception error ASP.NET MVC 为什么我在 Asp.Net Core 日志中收到“不支持 POST 请求”? - Why am I getting “POST requests are not supported” in my Asp.Net Core log? 当我尝试上传图像 ASP.NET MVC 4 时,我收到“用户代码未处理 NullReferenceException”的错误 - I am getting error of "NullReferenceException was unhandled by user code" while i try to upload Image ASP.NET MVC 4 ASP.NET MVC Core和Dapper中的全局异常/错误处理 - Global exception/error handling in asp.net mvc core and dapper 为什么在用测试数据填充数据库时出现异常(EF Core - ASP-NET Core) - Why am I getting an exception when filling the database with test data (EF Core - ASP-NET Core) ASP.NET Core Web API &amp; Entity Framework Core; 为什么我收到这个错误? - ASP.NET Core Web API & Entity Framework Core; why am I getting this error? 异常处理 ASP .NET Core MVC 6 - Exception handling ASP .NET Core MVC 6 处理asp.net核心中的异常? - Handling exception in asp.net core? ASP.Net Core 异常处理中间件 - ASP.Net Core exception handling middleware
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM