khellang / Middleware

Various ASP.NET Core middleware
MIT License
811 stars 112 forks source link

Custom ProblemDetailsFactory Fails while Return BadRequest() Action Result #172

Closed blogcraft closed 2 years ago

blogcraft commented 2 years ago

I have a CustomProblemDetailsFactory

and implement the CreateProblemDetails Method.

If in my controller y return an BadRequest("Message");. The CreateProblemDetails Method works fine and recieves a 400 statusCode as a parameter.

But if my controller returns a BadRequest(); The CreateProblemDetails method receives a null statusCode parameter.

Help! :)

khellang commented 2 years ago

Hello @blogcraft! 👋🏻

Hmm. What does the response look like? I'm just wondering whether it's the middleware or MVC that's producing a response.

Since the response doesn't contain any content, it should just set the status code in MVC and let it flow back up to the middleware, which should call into the factory to produce a problem response based on the status code.

We only handle ObjectResult at the MVC level (assuming you've called AddProblemDetailsConventions) since otherwise it would flush the response and prevent the middleware from returning a problem response:

https://github.com/khellang/Middleware/blob/48b8d9e1f9b4ca0ef8520b9d66ba8ab270289757/src/ProblemDetails/Mvc/ProblemDetailsResultFilter.cs#L30-L34

khellang commented 2 years ago

Ah, I see. In the middleware we call CreateProblemDetails with only the HttpContext:

https://github.com/khellang/Middleware/blob/48b8d9e1f9b4ca0ef8520b9d66ba8ab270289757/src/ProblemDetails/ProblemDetailsMiddleware.cs#L77-L90

While in the MVC filter, we also pass a status code from the result:

https://github.com/khellang/Middleware/blob/48b8d9e1f9b4ca0ef8520b9d66ba8ab270289757/src/ProblemDetails/Mvc/ProblemDetailsResultFilter.cs#L59-L64

I encourage you to do what the default factory does (which I think is the intended behavior of the API (it's a bit weird, but out of our control)):

https://github.com/khellang/Middleware/blob/48b8d9e1f9b4ca0ef8520b9d66ba8ab270289757/src/ProblemDetails/ProblemDetailsFactory.cs#L99

blogcraft commented 2 years ago

Setting the status code from the context response did it!

Thanks a lot!