Custom response when Model binding fails ASP.NET Core API

Custom response when Model binding fails ASP.NET Core API

Content Index :

Custom response when Model binding fails ASP.NET Core API
Tag : chash , By : Ray
Date : November 24 2020, 12:01 PM

wish helps you In reference to this post, to add a custom response based on your usecase add the below code In Startup
services.Configure<ApiBehaviorOptions>(o =>
    o.InvalidModelStateResponseFactory = actionContext =>
        new ResponseObject("403", "processing error");
 class ResponseObject{
   public string Status;
   public string Message;
   ResponseObject(string Status, string Message){
     this.Status = Status;
     this.Message= Message;

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Writing custom 500 response body works with IIS Express, but fails on IIS ASP.Net Core 1.0

Tag : asp.net-core , By : delphiace
Date : March 29 2020, 07:55 AM
I hope this helps . As Kiran mentions above, I was not setting the content length. This solved the problem. Now both of these solutions work fine on IIS:
string msg = Newtonsoft.Json.JsonConvert.SerializeObject(new { message = message, incidentId = incidentId });
byte[] bytes = Encoding.UTF8.GetBytes(msg);

context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.HttpContext.Request.ContentLength = bytes.Length;
await context.HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
var result = new JsonResult(new { message = message, incidentId = incidentId });
result.StatusCode = StatusCodes.Status500InternalServerError;
context.Result = result;

Custom model binding through body in ASP.Net Core

Tag : asp.net-core , By : user157654
Date : March 29 2020, 07:55 AM
it helps some times I found a solution. The body of a HTTP Post request using ASP.NET Core can be obtained in a custom model binder using this lines of code
string json;
using (var reader = new StreamReader(bindingContext.ActionContext.HttpContext.Request.Body, Encoding.UTF8))
   json = reader.ReadToEnd();

How to do custom model binding in Asp.Net Core MVC

Tag : chash , By : ZsA
Date : March 29 2020, 07:55 AM
I wish did fix the issue. In this scenario, you don't need to create your own binder. The built-in model binder has already done it for you. So the easiest way is to let the ASP.NET Core bind the model automatically:
public async Task SignIn(
    [FromForm]SignInRequestModel request,  // the [FromForm] is required when you're using an ApiController
    string returnUrl = null
public Task BindModelAsync(ModelBindingContext bindingContext)
    if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); }
    var request = bindingContext.ActionContext.HttpContext.Request;

    var model = new SignInRequestModel();
    var pis = typeof(SignInRequestModel).GetProperties();
    foreach(var pi in pis){
        var pv = bindingContext.ValueProvider.GetValue(pi.Name); // prop value
    bindingContext.Result = ModelBindingResult.Success(model);
    return Task.CompletedTask;

Custom Model Binding in Asp .Net Core

Tag : chash , By : LucaN
Date : March 29 2020, 07:55 AM

ASP.NET Core customize the error when model binding fails

Tag : asp.net , By : user160048
Date : March 29 2020, 07:55 AM
wish of those help You can customize your error message from Startup class in ConfigureServices method. You can see details Microsoft document.
Here is an example -
services.AddMvc(options =>
                var iStrFactory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
                var L = iStrFactory.Create("ModelBindingMessages", "WebUI"); // Resource file location 
                options.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) => L["The value '{0}' is invalid."]);

                options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) => L["The field {0} must be a number."]);
                options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) => L["A value for the '{0}' property was not provided.", x]);
                options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => L["The value '{0}' is not valid for {1}.", x, y]);
                options.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() => L["A value is required."]);
                options.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) => L["The supplied value is invalid for {0}.", x]);
                options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) => L["Null value is invalid.", x]);
Related Posts Related QUESTIONS :
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • Losing special unicode characters in encryption (C#)
  • Getting stored procedure returned value instead of row affected
  • How can I construct HTML using NameValuePair in android?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com