Extending WebApi response using OWIN Middleware

2019-07-17 19:54发布

问题:

I have a WebApi project based on OWIN, and I wanted to extend the result of WebApi call with some additional data, for example add localization data to response.

Initial idea was to inject that logic in a pipeline and once we get a result of API call I just have wrap that json with wrapper that will contain translation and some additional properties like time of execution.

So I wrote my own middleware put it after UseWebApi() but it's not executed because WebApi doesn't call "Next" in case it handles the request

So the question is:

How can I modify/extend Json returned by WebApi middleware? Any other ideas how to handle such a problem with an action that has to be executed for all requests?

Thanks

回答1:

Regarding the middleware: you need to place your middleware before UseWebApi, and put your logic after invoking the next middleware; in this case your code well execute after Web API is done processing the request.

You might also want to check the following blog post, it discusses the same scenario of yours: http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information