Asp.net Core发送邮件时IFormFile附件始终为null问题
IFormFile 始终返回null的解决办法
你的问题核心原因是HTML表单未配置文件上传所需的编码类型,另外还有几个需要检查的细节,逐一解决如下:
1. 给表单添加enctype="multipart/form-data"属性
默认的表单编码格式无法处理文件上传,必须显式声明multipart/form-data,修改后的表单代码如下:
<form asp-action="SendMail" asp-controller="Home" method="post" enctype="multipart/form-data" class="form-container signin-form"> <h2 style="font-family:Calibri">Bilgilerinizi Doldurun ve Dosyayı Seçin</h2> <input type="text" class="form-control mt-4" id="weexformname" name="weexformname" style="font-family:Calibri;border-radius:20px" placeholder="İsim Soyisim" aria-label="Username" aria-describedby="basic-addon1"> <input type="text" class="form-control mt-4" id="weexformemail" name="weexformemail" style="font-family:Calibri;border-radius:20px" placeholder="E-Mail" aria-label="Email" aria-describedby="basic-addon1"> <input type="number" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" maxlength="12" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" placeholder="Telefon Numarası" style="font-family:Calibri;border-radius:20px" class="form-control mt-4" aria-label="Phone" id="weexformphone" name="weexformphone" required /> <input class="form-control-file mt-4" type="file" name="AttachedFile"> <textarea type="text" class="form-control mt-4" style="font-family:Calibri;border-radius:20px" aria-label="Message" rows="3" placeholder="Bize Yazın" id="weexformmessage" name="weexformmessage" aria-describedby="basic-addon1"></textarea> <button type="submit" class="button-62 mt-4" role="button" style="float:right;font-family:Calibri">Gönder</button> </form>
2. 确认参数绑定一致性
检查控制器方法中的IFormFile AttachedFile参数名,与表单中file输入框的name="AttachedFile"是否完全一致——你的代码里这点符合要求,无需修改。
3. 配置文件上传大小限制(可选)
若上传文件超过ASP.NET Core默认大小限制,也会导致IFormFile为null。可在Program.cs中添加配置调整限制:
builder.Services.Configure<FormOptions>(options => { // 设置最大上传文件大小为10MB,可按需调整 options.MultipartBodyLengthLimit = 10 * 1024 * 1024; });
4. 控制器代码添加空值判断
为避免空引用异常,添加附件前先检查AttachedFile有效性:
if (AttachedFile != null && AttachedFile.Length > 0) { message.Attachments.Add(new Attachment(AttachedFile.OpenReadStream(), AttachedFile.FileName)); }
内容的提问来源于stack exchange,提问作者Hamza
相关产品推荐
相关产品推荐

