Hi friends, have you ever wanted to make post requests while choosing to pass a body or not ?. Some times you may want more flexibility in your post requests. You built a REST API and you want the user of the API to be free to pass a null value as the body of a post request if he wanted to. Here is a short post explaining how to allow optional FormBody in Asp.net core.
Asp.net core is very flexible and provides us the IModelBinder interface. Which provides the contract to implement model bindings. Basically, what we will do is get the data passed via the post request as a json string, convert it and use and pass the success result when everything does well. For more flexibility, we use the generics to set a type for the model when we want.
public class EmptyBodyModelBinder<T> : IModelBinder
public async Task BindModelAsync(ModelBindingContext bindingContext)
var stream = bindingContext.HttpContext.Request.Body;
using var reader = new StreamReader(stream);
var jsonbody = await reader.ReadToEndAsync();
var obj = JsonConvert.DeserializeObject<T>(jsonbody);
bindingContext.Result = ModelBindingResult.Success(obj);
Using the model binding is simple inside your post requests, you can do this:
public async Task<IActionResult> CreateStoreItem([FromBody, ModelBinder(BinderType = typeof(EmptyBodyModelBinder<StoreItem>))]StoreItem item)
Asp.net core is very flexible and allows you to do most of what you want when building REST APIs with it. With this you allowed an Optional FormBody in asp.net core REST API. You might be interested by this post about Xamarin Forms Navigation: