简体   繁体   中英

Passing data from a ModelBinder to a custom InputFormatter

The Context : In a WebAPI under Asp.net Core 2.1, I must create a POST endpoint, [server]/MyController/{Parameter1}/MoreRouteThing/ . I have to create a custom IInputFormatter because the body isn't readable by the default formatters.

The Problem : To be able to format the input, the IInputFormatter need to know the value of Parameter1 .

I implemented a custom IModelBinder that handles this model, wired everything in startup.cs using a custom IModelBinderProvider (probably overkill, but I wanted to understand the whole chain.)

Within the custom IModelBinder , I can access {Parameter1} using something akin bindingContext.ActionContext.RouteData.Values["Parameter1"] , but I have no idea how to pass that to the IInputFormatter . The former passes an InputFormatterContext to the latter, but nothing within that context object seems appropriate to store extra information.

So the Question : How to pass data from the IModelBinder to the IInputFormatter ? Should I instead parse the url/route directly from the IInputFormatter , hence making it aware of "where" it's located within the whole process? (seems unclean to me.)

The list of all formatters is transmitted through the constructor of the modelbinder and in the future one is selected that matches the specified condition. More details can be found in the source code: https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinder.cs and https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinderProvider.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM