简体   繁体   中英

Why am I getting 'The remote server returned an error: (401) Unauthorized.' from this code snippet?

So I copy-pasted the brief code snippet

public ActionResult Run()
{
    string apiKey = "ABCD-1234";
    string value = "http://www.google.com"; // a url starting with http or an HTML string

    using (var client = new WebClient())
    {
        // Build the conversion options 
        NameValueCollection options = new NameValueCollection();
        options.Add("apikey", apiKey);
        options.Add("value", value);

        // Call the API convert to a PDF
        MemoryStream ms = new MemoryStream(client.UploadValues("http://api.html2pdfrocket.com/pdf", options));

        // Make the file a downloadable attachment - comment this out to show it directly inside
        HttpContext.Response.AddHeader("content-disposition", "attachment; filename=myfilename.pdf");

        // Return the file as a PDF
        return new FileStreamResult(ms, "application/pdf");
    }
}

from http://www.html2pdfrocket.com/convert-csharp-to-pdf into my web application and am getting a 401 error with a stack trace like

[WebException: The remote server returned an error: (401) Unauthorized.] System.Net.WebClient.UploadValues(Uri address, String method, NameValueCollection data) +490
System.Net.WebClient.UploadValues(String address, NameValueCollection data) +35 Survey.Controllers.AnswersController.Run() +163
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14

I tried adding in client = UseDefaultCredentials = true; , to no avail.

Any other ideas I can try?

read this documentation

it's saying in API Authentication Section In case you don't have an account yet you can sign up for our 14-day free trial. To authenticate against our web service you're required to use your API key and username. These can be found on your profile page and dashboard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM