unosquare / embedio

A tiny, cross-platform, module based web server for .NET
http://unosquare.github.io/embedio
Other
1.45k stars 175 forks source link

The message of HttpException.BadRequest(message) does not in the response body. #543

Closed GF-Huang closed 2 years ago

GF-Huang commented 2 years ago

Describe the bug Well, the doc tell me it will include in the response, but it does not.

image

To Reproduce Steps to reproduce the behavior:

  1. image image

  2. image

Expected behavior The message should include in the response.

Desktop (please complete the following information):

GF-Huang commented 2 years ago

Crazy, the doc tricked me.

https://github.com/unosquare/embedio/blob/603c3deaf141fe7c79a609e02be106a2b3193c7f/src/EmbedIO/HttpExceptionHandler.cs#L133

GF-Huang commented 2 years ago

I found that because I set the OnHttpException to a custom event callback cause this issue, I mistook it for a simple event notification callback.

rdeago commented 2 years ago

Hello @GF-Huang, I was going to reply but I see you've found out the cause by yourself.

For the benefit of future users with similar issues: the presence of message and data parameters in the methods that create HTTP exceptions (HttpException.BadRequest etc.) do not imply that those parameters will be used in the response.

In particular, message will NOT change the HTTP status message (status code 400 will always be sent as 400 Bad Request).

The message and data parameters are just stored in the created exception (as properties IHttpException.Message and IHttpException.DataObject). It is up to HTTP exception handlers to use (or not use) message and data in the response they generate.

HTTP exception handlers are not just notification callbacks, as @GF-Huang found out: they are in charge of creating an appropriate response, according to the exception thrown and the type of response the client will accept. For instance, the default HTTP exception handler generates a HTML response, which is useful for debugging and may be appropriate if the client is a browser trying to load a HTML page. When dealing with a Web API served by a WebApiModule, a JSON response is probably more suitable. For this reason each module and module group, as well as the whole server, may have its own HTTP exception handler.

To see how IHttpException.Message and IHttpException.DataObject are actually used, and how you can use them in your own HTTP exception handlers, have a look at the public methods of the HttpExceptionHandler class.