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"]}]}
Use ControllerBase. Content() method returns a ContentResult object. This method has several overloads, and we will be using an overload that accepts two string parameters. The first string represents the content of the HTML while the last is the content-type which for HTML is "text/html" .
One of the core benefits of REST is its separation of representation (encoding) from the underlying resource being accessed. It's perfectly fine to return HTML if the client requests it as a preference via the Accept header.
So, if you want to return a View you need to use the simple ol' Controller . The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage ( View ) for a user you don't use the Web API.
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With