Allow optional FormBody in asp.net core REST API - Cool Coders about:reader?url=https://doumer.me/allow-optional-formbody-in-asp-n...
doumer.me
Allow optional FormBody in asp.net
core REST API - Cool Coders
2-3 minutes
.Net Core , Asp.net core ,
03 Jun
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.
The Code
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
1 of 3 11/28/2020, 4:13 PM
Allow optional FormBody in asp.net core REST API - Cool Coders about:reader?url=https://doumer.me/allow-optional-formbody-in-asp-n...
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:
[HttpPost]
public async Task<IActionResult>
CreateStoreItem([FromBody, ModelBinder(BinderType =
typeof(EmptyBodyModelBinder<StoreItem>))]StoreItem
item)
//...
If you like this post, don’t hesitate to follow me on Twitter or
Github and subscribe to this page’s notifications to stay
updated with new articles or like my page on Facebook.
2 of 3 11/28/2020, 4:13 PM
Allow optional FormBody in asp.net core REST API - Cool Coders about:reader?url=https://doumer.me/allow-optional-formbody-in-asp-n...
Conclusion
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:
References
https://github.com/dotnet/aspnetcore/issues
/6878#issuecomment-595515755
Follow me on social media and stay updated
3 of 3 11/28/2020, 4:13 PM