disassemble-number-5
disassemble-number-5

Reputation: 995

How to return html page from WebApi action?

I'm looking for a WebApi example where the default route will return a given html page to the caller. I've got the route and action set up as follows. I just want to send him the index.html page, not redirect, because he's in the right place.

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

If I"m using this wrong, what's the better approach and can you point me to an example?

WebApi 2 with .NET 4.52

Edit: Hmm, improved it, but getting json header back instead of page content.

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

Upvotes: 30

Views: 41894

Answers (2)

Vivek
Vivek

Reputation: 2123

For ASP.NET Core (not ASP.NET Standard) then if it's a static html file (which it looks like), use the static resource options:

Static files in ASP.NET Core

Upvotes: 3

Marcus Höglund
Marcus Höglund

Reputation: 16811

One way to do this is to read the page as a string and then send it in a response of content type "text/html".

Add namespace IO:

using System.IO;

In the controller:

[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;
}

Upvotes: 46

Related Questions