如何从WCF WebAPI WebGet返回原始html

Swo*_*ter 9 html rest wcf wcf-web-api

我有一个自托管的WCF服务作为Windows服务运行使用WebAPI来处理REST的东西,它工作得很好.

我意识到我应该真的使用IIS或类似的方式来播出实际的网页,但有没有办法获得服务调用以返回"只是"HTML?

即使我指定"BodyStye Bare",我仍然会获得围绕实际HTML的XML包装器,即

<?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");
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,还是应该放弃?

Dar*_*ler 16

bodystyle属性对WCF Web API没有影响.以下示例将起作用.这不一定是最好的方式,但它应该工作假设我没有做任何错别字:-).

[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; 
}
Run Code Online (Sandbox Code Playgroud)

将文件作为流读取并使用StreamContent而不是StringContent可能更有意义.或者很容易创建自己的FileContent类,接受文件名作为参数.

并且,自托管选项与使用IIS返回静态HTML一样可行.在封面下,他们使用相同的HTTP.sys内核模式驱动程序来传递位.

  • 谢谢堆,这足以让我到那里,我只需要将一行更改为"response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");" (3认同)