Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return raw html from a WCF WebAPI WebGet

I have a self-hosted WCF service running as a windows service using the WebAPI to handle the REST stuff and it works great.

I realise that I should really use IIS or similar to dish out actual web pages, but is there ANY way to get a service call to return "just" html?

Even if I specify "BodyStye Bare", I still get the XML wrapper around the actual HTML, ie

<?xml version="1.0" encoding="UTF-8"?>
<string> html page contents .... </string>


[WebGet(UriTemplate = "/start", BodyStyle = WebMessageBodyStyle.Bare)]
public string StartPage()
{
    return System.IO.File.ReadAllText(@"c:\whatever\somefile.htm");
}

Is there any way to do this or should I give up?

like image 429
Swordblaster Avatar asked Nov 14 '11 04:11

Swordblaster


2 Answers

The bodystyle attribute has no effect on WCF Web API. The example below will work. It's not necessarily the best way of doing it, but it should work assuming I didn't make any typos :-).

[WebGet(UriTemplate = "/start")] 
public HttpResponseMessage StartPage() {
    var response = new HttpResponseMessage();
    response.Content = new StringContent(System.IO.File.ReadAllText(@"c:\whatever\somefile.htm"));
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response; 
}

It would probably make more sense to read the file as a stream and use StreamContent instead of StringContent. Or it is easy enough to make your own FileContent class that accepts the filename as a parameter.

And, the self-host option is just as viable way to return static HTML as using IIS. Under the covers they use the same HTTP.sys kernel mode driver to deliver the bits.

like image 64
Darrel Miller Avatar answered Nov 11 '22 21:11

Darrel Miller


You'll have to use a formatter that accepts "text/html" as content type and request the content type "text/html" in your request header.

If you don't add a formatter that handles the text/html, Web API falls back to the XML-formatter as default.

In your case the formatter doesn't need to format anything but just return your return value as you're returning formatted html already.

like image 38
Alexander Zeitler Avatar answered Nov 11 '22 20:11

Alexander Zeitler