How to display ASP.NET Core Pages error messages thrown by the framework

AT 0 Reputation points
2024-07-25T09:46:19.4866667+00:00

In my ASP.NET application, when a file upload exceeds the default allowed size limit by ASP.NET, instead of displaying an error message, the application shows a blank page. How can I configure my application to properly handle and display error messages, such as those related to the default file size limits, instead of showing a blank page?

I have no default error handling page.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Brando Zhang-MSFT 3,446 Reputation points Microsoft Vendor
    2024-07-25T11:47:43.78+00:00

    Hi @AT,

    If you want to handle the 500 error inside the asp.net core, I suggest you could use the UseExceptionHandler method, this method is used to show the custom error page when the exception thrown.

    More details, you could refer to below codes:

    1.Create a Error handler view inside the home controller:

            [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
            public IActionResult Error()
            {
                return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
            }
    

    View:

    @model ErrorViewModel
    @{
        ViewData["Title"] = "Error";
    }
    <h1 class="text-danger">Error.</h1>
    <h2 class="text-danger">An error occurred while processing your request.</h2>
    @if (Model.ShowRequestId)
    {
        <p>
            <strong>Request ID:</strong> <code>@Model.RequestId</code>
        </p>
    }
    <h3>Development Mode</h3>
    <p>
        Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
    </p>
    <p>
        <strong>The Development environment shouldn't be enabled for deployed applications.</strong>
        It can result in displaying sensitive information from exceptions to end users.
        For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
        and restarting the app.
    </p>
    

    Error model:

        public class ErrorViewModel
        {
            public string? RequestId { get; set; }
            public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
        }
    

    Modify then program.cs:

    ...
    app.UseExceptionHandler("/Home/Error");
    ...
    
    0 comments No comments

  2. SurferOnWww 2,491 Reputation points
    2024-07-26T01:17:21.4166667+00:00

    Please consider the validation attribute to validate the file size at the client side using HTML5 File API and JavaScript. Below is sample which includes a custom validator of ASP.NET Core 3.1 MVC used for validating the size and type of uploading file:

    Model and Custom Validator

    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using System.ComponentModel.DataAnnotations;
    using System.Text.RegularExpressions;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using System.Globalization;
    using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc.Rendering;
     
    namespace MvcCoreApp.Models
    {
        // Model
        // See attribute [FileValidation(50000, "image/jpeg")] below.
        // file size is limited to 50000 and file type to "image/jpeg"
        public class FileUpload
        {
            [Required(ErrorMessage = "{0} is required.")]
            public string Name { get; set; }
     
            [Display(Name = "Upload file")]
            [Required(ErrorMessage = "{0} is required.")]
            [FileValidation(50000, "image/jpeg")]
            public IFormFile PostedFile { get; set; }
        }
     
        // Custom validator attribute
        [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
        public class FileValidationAttribute : ValidationAttribute, 
                                               IClientModelValidator
        {
            private readonly long size;
            private readonly string type;
     
            public FileValidationAttribute(long size, string type)
            {
                this.size = size;
                this.type = type;
                this.ErrorMessage = "{0} must be less than {1} byte, {2}";
            }
     
            public override string FormatErrorMessage(string displayName)
            {
                return String.Format(CultureInfo.CurrentCulture, 
                                     ErrorMessageString, displayName, 
                                     this.size, this.type);
            }
     
            public override bool IsValid(object value)
            {
                var postedFile = value as IFormFile;
     
                if (postedFile == null || postedFile.Length == 0)
                {
                    return false;
                }
     
                if (postedFile.Length <= this.size && 
                    postedFile.ContentType == this.type)
                {
                    return true;
                }
     
                return false;
            }
    
            // method for IClientModelValidator
            public void AddValidation(ClientModelValidationContext context)
            {
                MergeAttribute(context.Attributes, "data-val", "true");
                var errorMessage = FormatErrorMessage(
                    context.ModelMetadata.GetDisplayName());
                MergeAttribute(context.Attributes, 
                    "data-val-filevalidation", errorMessage);
                MergeAttribute(context.Attributes, 
                    "data-val-filevalidation-size", this.size.ToString());
                MergeAttribute(context.Attributes, 
                    "data-val-filevalidation-type", this.type);
            }
     
            // helper used in above AddValidation method
            private bool MergeAttribute(IDictionary<string, string> attributes, 
                                        string key, string value)
            {
                if (attributes.ContainsKey(key))
                {
                    return false;
                }
                attributes.Add(key, value);
                return true;
            }
        }
    }
    

    View

    @model MvcCoreApp.Models.FileUpload
     
    @{
        ViewData["Title"] = "Upload";
    }
     
    <h1>Upload</h1>
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form asp-action="Upload" enctype="multipart/form-data">
                <div asp-validation-summary="ModelOnly" class="text-danger">
                </div>
                <div class="form-group">
                    <label asp-for="Name" class="control-label"></label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name" class="text-danger"></span>
                </div>
     
                <div class="form-group">
                    <label asp-for="PostedFile" class="control-label"></label>
                    <input type="file" asp-for="PostedFile" />
                    <br />
                    <span asp-validation-for="PostedFile" class="text-danger">
                    </span>
                </div>
     
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
     
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
     
     
    <script type="text/javascript">
        //<![CDATA[
        $.validator.addMethod("filevalidation",
            function (value, element, parameters){
                // confirm if HTML5 File API is supported
                if (window.File && window.FileList) {
     
                    if (element.files[0] == undefined ||
                        element.files[0] == null) {
                        return true;
                    }
     
                    if (element.files[0].type != parameters.type) {                    
                        return false;
                    }
     
                    if (element.files[0].size > Number(parameters.size)) {
                        return false;
                    }
     
                    return ture;
                } else {
                    return ture;
                }
            });
     
        $.validator.unobtrusive.adapters.
            add("filevalidation", ["type", "size"], function (options) {
     
                var value = {
                    size: options.params.size,
                    type: options.params.type
                };
     
                setValidationValues(options, "filevalidation", value);
            });
     
        // helper method copied from jquery.validate.unobtrusive.js
        function setValidationValues(options, ruleName, value) {
            options.rules[ruleName] = value;
            if (options.message) {
                options.messages[ruleName] = options.message;
            }
        }
        //]]>
    </script>
    }
    

    Comtroller / Action Method

    using System;
    using System.Collections.Generic;
    using Microsoft.AspNetCore.Mvc;
    using MvcCoreApp.Models;
    using Microsoft.AspNetCore.Http;
    using System.IO;
    using Microsoft.AspNetCore.Mvc.Rendering;
     
    namespace MvcCoreApp.Controllers
    {
        public class ValidationController : Controller
        {
            public IActionResult Upload()
            {
                return View();
            }
     
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult Upload(FileUpload model)
            {
                string result = "";
                IFormFile postedFile = model.PostedFile;
     
                if (ModelState.IsValid)            
                {
                    string filename = Path.GetFileName(postedFile.FileName);
                     
                    result = filename + " (" + postedFile.ContentType + ") - " +
                            postedFile.Length + " bytes uploaded";
                }
                else
                {
                    result = "upload fail";
                }
     
                ViewBag.Result = result;
                return View();
            }
        }
    }
    
    0 comments No comments