M_Row
M_Row

Reputation: 119

How to return HTML from ASP.NET Web API when given url

I want to create a WEB API that will accept a url and return the url's "HTML" page. Please how should I do this? I believe I have the wrong code. HI am so new to this. Thanks*

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("https://myurl.com");
    response.Content.Headers.ContentType = new    MediaTypeHeaderValue("text/html");
    return response;
}

Upvotes: 0

Views: 4734

Answers (2)

Alexander
Alexander

Reputation: 1263

My extension for AspNetCore:

    public static ContentResult GetDashboardAsHtml(this AbpController controller)
    {
        var request = WebRequest.Create($"{controller.Request.Scheme}://{controller.Request.Host}/hangfire");

        using var response = request.GetResponse();
        using var streamReader = new System.IO.StreamReader(response.GetResponseStream());
        return new ContentResult
        {
            Content = streamReader.ReadToEnd().Trim(),
            ContentType = "text/html"
        };
    }

Upvotes: 0

dan richardson
dan richardson

Reputation: 3939

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

Upvotes: 2

Related Questions