0

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;
}
1
  • "believe I have the wrong code" why? Please describe the error or unexpected behaviour you are getting. Commented Jul 16, 2015 at 13:36

2 Answers 2

2

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;
}       
Sign up to request clarification or add additional context in comments.

4 Comments

Yes! Thanks but I am getting this error: " 'System.Net.WebRequest': type used in a using statement must be implicitly convertible to 'System.IDisposable' ". do you know what this is?
Must not be IDisposable. Just remove the using around that line - updated code
Great That worked fine... But I have one more question: If I wanted to add this to API Controller (that function) to an already made MVC Controller, how till that work? or rephrase my question I want the var "response" to be accessible in my normal MVC controller. How can I link the two? Thanks!!!
Normal controllers, and API Controllers work slightly different, otherwise if there were the same type you could have a base class with the response in it, that any derived class could access.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.