문제

As we know by default, Web API framework has formatters that can produce JSON or XML If you want to produce some other types of output, then in many places i've read it is required to implement custom media type formatter that will do what you want. But f.e. i need to return raw HTML from my Web API controller, and if i create HttpResponseMessage this way:

 response = new HttpResponseMessage()
                        {
                            Content = new StringContent(
                                "<p>Hello world</p>",
                                Encoding.UTF8,
                                "text/html")
                        };

Then I have raw HTML in my response that browser will recognize and render. My question actually Why it is works without using any custom formatter, and in which case i need to create one, and in which I shouldn't.

도움이 되었습니까?

해결책

Formatters give your service the flexibility to respond to a client with the same data but in an arbitrary format depending on what the client has asked for. If a client asks for application/json, your service will use the JSON formatter to respond with JSON.

As far as I know, formatters are only applied in the case where your method directly returns the object to be serialized. In your case, regardless of the media type that the client has asked for, you're returning a HttpResponseMessage with a string containing html content.

Generally, you'll want to use formatters if you want your service to potentially serve up the same data in different formats depending on the Accept header that the client has specified.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top