2016-06-29 4 views
14

기본 경로가 지정된 html 페이지를 호출자에게 반환하는 WebApi 예제를 찾고 있습니다. 경로와 액션을 다음과 같이 설정했습니다. 나는 그가 올바른 장소에 있기 때문에 리디렉션하지 않고 index.html 페이지를 보내려합니다. 나는 "이 잘못을 사용하고 있습니다 경우WebApi 작업에서 HTML 페이지를 반환하는 방법은 무엇입니까?

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"); 
} 

는 더 나은 방법이고 당신은 무엇을 예를 들어 저를 가리킬 수 있습니다

WebApi 2 .NET 4.52

편집과 : 흠, 그것을 개선하지만, 페이지 내용의 다시 대신 JSON 헤더를 받고.

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"]}]} 

답변

25

이 작업을 수행하는 한 가지 방법은 페이지를 문자열로 읽은 다음 내용 유형이 "text/html"인 응답으로 보내는 것입니다.

추가 네임 스페이스 IO : 컨트롤러에서

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

그것을, 그냥 정적 자원 옵션을 사용하여 (이 모양) 정적 HTML 파일이 있다면. https://docs.asp.net/en/latest/fundamentals/static-files.html

+4

그렇게 보이는이 Asp.Net 코어입니다. 용서하십시오. 정적 파일을 제공하기 위해 WebApi 코드를 변경할 위치를 이해하지 못했습니다. Configure 또는 WebHostBuilder 메소드가 없습니다. –

관련 문제