2016-06-29 19 views
14

WebApi örneğini arıyorum, bu durumda varsayılan yol, verilen html sayfasını arayan kişiye döndürecektir. Rota ve eylem şu şekilde ayarlanmış. Sadece ona index.html sayfasını göndermek istiyorum, yönlendirmek değil, çünkü doğru yerde. Ben "Bu yanlış kullanıyorum varsaWebApi eyleminden html sayfası nasıl iade edilir?

http://localhost/Site  // load index.html 

// WebApiConfig.cs 
config.Routes.MapHttpRoute(
    name: "Root", 
    routeTemplate: "", 
    defaults: new { controller = "Request", action = "Index" } 
); 

// RequestControlller.cs 
    [HttpGet] 
[ActionName("Index")] 
public HttpResponseMessage Index() 
{ 
    return Request.CreateResponse(HttpStatusCode.OK, "serve up index.html"); 
} 

, iyi bir yaklaşım olduğunu ve ne bir örnek beni işaret edebilir

WebAPI 2 NET 4,52

Düzenleme ile:? Hmm, bunu geliştirilmiş, ancak sayfa içeriğinin geri yerine json başlığını almak.

public HttpResponseMessage Index() 
{ 
    var path = HttpContext.Current.Server.MapPath("~/index.html"); 
    var content = new StringContent(File.ReadAllText(path), Encoding.UTF8, "text/html"); 
    return Request.CreateResponse(HttpStatusCode.OK, content); 
} 

{"Headers":[{"Key":"Content-Type","Value":["text/html; charset=utf-8"]}]} 

cevap

25

Bunu yapmanın bir yolu, sayfayı bir dize olarak okumak ve ardından "text/html" içerik türünde bir yanıt olarak göndermektir.

Ekleme ad IO: kontrolörü olarak

using System.IO; 

:

[HttpGet] 
[ActionName("Index")] 
public HttpResponseMessage Index() 
{ 
    var path = "your path to index.html"; 
    var response = new HttpResponseMessage(); 
    response.Content = new StringContent(File.ReadAllText(path)); 
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); 
    return response; 
} 
1

o sadece statik kaynak seçeneklerini kullanmak (benzediğini) statik html dosyası buysa. https://docs.asp.net/en/latest/fundamentals/static-files.html

+4

Öyle görünüyor Asp.Net Çekirdek için. Affet beni statik dosyaya hizmet vermek için WebApi kodunu değiştirmek için tam olarak anlamıyorum. Configure veya WebHostBuilder yöntemim yok. –