HttpGet возвращает ошибку 405

Используя ASP Web API, я создаю метод, который принимает идентификатор, затем доставляет файл PDF, затем использует Google Docs Viewer или аналогичную службу для просмотра файла,

Код выглядит примерно так:

[HttpGet]
public HttpResponseMessage GetAttachment(string id)
{
    try {
        string mapping = @"\\192.168.3.3\Archieve";
        string sourcedir = @"\Digital\";
        string filename = id + ".pdf";
        string sourceFullPath = mapping + sourcedir + filename;
        byte[] dataBytes = new byte[0];

        // connect to other network using custom credential
        var credential = new NetworkCredential("user", "pass", "192.168.3.3");
        using (new NetworkConnection(mapping, credential)) {
            dataBytes = File.ReadAllBytes(sourceFullPath);
        }

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StreamContent(new MemoryStream(dataBytes));
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = filename;
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        return response;
    }
    catch (Exception ex) {
        return Request.CreateResponse(HttpStatusCode.Gone, ex.Message);
    }
}

С помощью этого кода я могу загрузить PDF-файл, когда открываю ссылку в веб-браузере, но когда я пытаюсь отобразить его с помощью Google Docs Viewer, вот так

https://docs.google.com/viewerng/viewer?url=http://myserver/webapi/api/File/GetAttachment/0317101532

Google не смог отобразить файл без ошибок,

И когда я использую другой сервис, как https://www.pdfescape.com/open/ ошибка The remote server returned an error: (405) Method Not Allowed.

РЕДАКТИРОВАТЬ: Я думаю, что и для просмотра Google Docs и pdfescape нужна прямая ссылка на файл, могу ли я создать прямую ссылку на контроллере Web API?

1 ответ

Решение

Попробуйте скопировать файл на локальный, а затем вернуть ссылку на файл, что-то вроде этого

[HttpGet]
public IHttpActionResult GetAttachment(string id)
{
    try {
        string mapping = @"\\192.168.3.3\Archieve";
        string sourcedir = @"\Digital\";
        string filename = id + ".pdf";
        string sourceFullPath = mapping + sourcedir + filename;
        byte[] dataBytes = new byte[0];

        // connect to other network using custom credential
        var credential = new NetworkCredential("user", "pass", "192.168.3.3");
        using (new NetworkConnection(mapping, credential)) {
            dataBytes = File.ReadAllBytes(sourceFullPath);
        }

        // write file to local
        string destFullPath = string.Format("{0}/Content/Data//{2}", HttpContext.Current.Server.MapPath("~"), filename);
        File.WriteAllBytes(destFullPath, dataBytes);

        // return the file name, 
        return Ok(filename);

        // then you can view your docs using Google Viewer like this
        // https://docs.google.com/viewer?url=http://[YOUR_SERVER_BASE_URL]/content/data/[FILENAME]
    }
    catch (Exception ex) {
        return Content(HttpStatusCode.PreconditionFailed, ex.Message);
    }
}

Не забудьте добавить необходимые разрешения в папку "Контент"

Другие вопросы по тегам