Return HTML from ASP.NET Web API
ASP.NET Core. Approach 1
If your Controller extends ControllerBase
or Controller
you can use Content(...)
method:
[HttpGet]
public ContentResult Index()
{
return base.Content("<div>Hello</div>", "text/html");
}
ASP.NET Core. Approach 2
If you choose not to extend from Controller
classes, you can create new ContentResult
:
[HttpGet]
public ContentResult Index()
{
return new ContentResult
{
ContentType = "text/html",
Content = "<div>Hello World</div>"
};
}
Legacy ASP.NET MVC Web API
Return string content with media type text/html
:
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("<div>Hello World</div>");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
How to return html page from WebApi action?
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;
}
Return HTML from ASP.NET Web API ASP.NET Core 2 and get http status 406
As KTCO pointed out here :
Starting with AspNetCore 2.0, it's recommended to use
ContentResult
instead of theProduce
attribute
The solution is:
[HttpGet]
public ContentResult Get()
{
return new ContentResult {
ContentType = "text/html",
StatusCode = (int) HttpStatusCode.OK,
Content = "<html><body>Welcome</body></html>"
};
}
There is no need to change AddMvc
(and there is no Produce
attribute, of course).
I hope this helps someone.
return html file from .Net Core api
Thanks for @Marcus-h feedback and answer, I got it solved by using [Produces("text/html")]
and having the return as string
, so the full code is:
namespace server{
[Route("api/[controller]")]
public class FileController : Controller{
[HttpGet]
[Produces("text/html")]
public string Get()
{
string responseString = @"
<title>My report</title>
<style type='text/css'>
button{
color: green;
}
</style>
<h1> Header </h1>
<p>Hello There <button>click me</button></p>
<p style='color:blue;'>I am blue</p>
";
return responseString;
}
}
}
To get it opened in a browser window, i used:
var report = window.open('', 'myReport', 'location=no,toolbar=0');
// or var report = window.open(''); // if I need the user to be able to use the browser actions, like history
report.document.title = 'My report'; // if title not added in the server code
fetch('http://localhost:60000/api/File', {
method: 'get'
})
.then(function(response) {
return response.text();
}).then(function(text) {
report.document.body.innerHTML = text;
});
How to return HTML from ASP.NET Web API when given url
Do you mean do something like this?
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
System.Net.WebRequest req = System.Net.WebRequest.Create("https://myurl.com");
using (System.Net.WebResponse resp = req.GetResponse())
using (System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream()))
response.Content = sr.ReadToEnd().Trim();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
Webapi returns html page instead of json
I returned response as:
actionContext.Response = actionContext.Request.CreateResponse<string>(HttpStatusCode.BadRequest, "Unauthorized user");
and it returned "Unauthorized user"
instead of whole html page.
ASP.NET MVC Core WebAPI project not returning html
You can use ContentResult
, which inherits ActionResult
. Just remember to set ContentType
to text/html
.
public class MyModuleController : Controller
{
[HttpGet]
public IActionResult Get()
{
var content = "<html><body><h1>Hello World</h1><p>Some text</p></body></html>";
return new ContentResult()
{
Content = content,
ContentType = "text/html",
};
}
}
It will return a correct Content-Type:
Which will cause the browser to parse it as HTML:
Authorized API returns HTML when the controller is hit and not the content
I have a similar setup, the only difference is that you need to specify the specific auth policy in your Authorize attribute. In your "MyController" change your Authorize attribute to:
[Authorize(LocalApi.PolicyName)]
This requirement is shown in the IdenityServer docs at:
https://identityserver4.readthedocs.io/en/latest/topics/add_apis.html
Related Topics
Bundling Not Working in MVC5 When I Turn on Release Mode
Does C# Have an Equivalent to JavaScript's Encodeuricomponent()
C# Equivalent to Java's Charat()
C# Namespace Alias - What's the Point
How to Get the "Friendly" Os Version Name
How to Unregister 'Anonymous' Event Handler
Entity Framework/Linq Expression Converting from String to Int
Escape Curly Brace '{' in String.Format
How to Get the CPU Temperature
What Is the Purpose of Anonymous { } Blocks in C Style Languages
Publishing a Website Is Not Updating My CSS Bundles
JavaScript Date to C# via Ajax
Does Java Have Something Similar to C# Properties
Using Reflection in C# to Get Properties of a Nested Object
How to Extract a File from an Embedded Resource and Save It to Disk