使用 Web API 的 ApiController 编写接口,实现前端预览网站根目录下的 1.pdf 文件内容。

首先,创建一个继承自 'ApiController' 的类,并在其中添加一个方法来处理请求。使用 'FileResult' 返回文件给前端。

以下是一个示例代码:

using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;

public class PdfController : ApiController
{
    public HttpResponseMessage Get()
    {
        string filePath = HttpContext.Current.Server.MapPath('~/1.pdf');

        if (File.Exists(filePath))
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue('application/pdf');
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, 'File not found');
        }
    }
}

代码中,首先获取文件路径,并检查文件是否存在。如果存在,创建一个 'HttpResponseMessage' 对象,并将文件流设置为其内容。然后将内容类型设置为 'application/pdf'。如果文件不存在,返回一个 'HttpStatusCode.NotFound' 错误响应。

在 WebApiConfig.cs 文件中添加以下代码,启用 Web API 路由:

config.Routes.MapHttpRoute(
    name: 'PdfApi',
    routeTemplate: 'api/pdf',
    defaults: new { controller = 'Pdf' }
);

完成上述步骤后,即可通过访问 '/api/pdf' 路径获取 1.pdf 文件的预览。

使用 Web API ApiController 编写接口预览 PDF 文件

原文地址: https://www.cveoy.top/t/topic/qfKp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录