2012-10-04 67 views
1

使用System.Web.Http.SelfHost等。我如何發送一個HTML頁面到瀏覽器?如何發送html到C#SelfHost控制檯應用程序

目前,在谷歌Chrome瀏覽器它通過文本。我找不到如何將標題更改爲text/html,我不知道這是否可以解決問題。

我試了一些附件的變化沒有成功。

Episode數據通過瀏覽器在Google Chrome瀏覽器中傳遞OK作爲Json,但在IE中它詢問我是否想要(O)筆或(S)大小。在IE中,html具有相同的結果。

我想從RAM,而不是磁盤發送的HTML。

爲簡潔起見,省略了錯誤處理。

代碼如下: -

using System; 
using System.IO; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Net.Http; 
using System.Net.Http.Formatting; 
using System.Web.Http; 
using System.Web.Http.SelfHost; 

namespace Console015 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      HttpSelfHostServer server = null; 

      using (StreamReader reader01 = new StreamReader("test01.html")) 
      { 
       LoginController.sPage = reader01.ReadToEnd(); 
      } 
      Console.WriteLine(LoginController.sPage); 

      String sUrl = "http://localhost:8080"; 
      var serverConfig = new HttpSelfHostConfiguration(sUrl); 
      serverConfig.Formatters.Clear(); 
      serverConfig.Formatters.Insert(0, new JsonMediaTypeFormatter()); 
      serverConfig.Routes.MapHttpRoute(
       name: "DefaultApiRoute", 
       routeTemplate: "endpoints/{controller}", 
       defaults: null 
       ); 

      server = new HttpSelfHostServer(serverConfig); 

      server.OpenAsync().Wait(); 

      Console.WriteLine("Listening At : " + sUrl + "/endpoints/episode"); 
      Console.ReadLine(); 
     } 
    } 

    public class LoginController : ApiController 
    { 
     public static string sPage = string.Empty; 
     public HttpResponseMessage GetLoginPage() 
     { 
      // Create a 200 response. 
      var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) 
      { 
       Content = new StringContent(sPage) 
      }; 

      Console.WriteLine("Returning Login Page"); 

      return response; 

     } 
    } 

    public class Episode 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public string ReleasedOn { get; set; } 
    } 

    public class EpisodeController : ApiController 
    { 
     public IList<Episode> GetAllEpisodes() 
     { 
      return new List<Episode> 
      { 
       new Episode {Id = 1, Name = "Episode 1", ReleasedOn =  DateTime.Now.AddDays(10).ToShortDateString()}, 
       new Episode {Id = 2, Name = "Episode 2", ReleasedOn =  DateTime.Now.AddDays(-5).ToShortDateString()}, 
       new Episode {Id = 3, Name = "Episode 3", ReleasedOn = DateTime.Now.AddDays(-3).ToShortDateString()}, 
       new Episode {Id = 4, Name = null, ReleasedOn = DateTime.Now.AddDays(0).ToShortDateString()}, 
      }; 
     } 
    } 
} 

的HTML測試數據是:

<!DOCTYPE html> 
<html> 
<body> 

    <h1>My First Heading</h1> 

    <p>My first paragraph.</p> 

</body> 
</html> 

回答

1

答案似乎是: response.Content.Headers.ContentType.MediaType =「text/html的「;

相關問題