代码之家  ›  专栏  ›  技术社区  ›  Desomph

NetCore API在POST请求中返回pdf文件

  •  1
  • Desomph  · 技术社区  · 6 年前

    我正在使用NET Core v2。0

    我试图接受一个以XML文件为主体的post请求,解析该请求,并返回生成的PDF文件。不必深入逻辑, 以下是我在控制器中的内容:

    public async Task<HttpResponseMessage> PostMe() {
            return await Task.Run(async () => {
                try {
                    using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) {
                        var serializer = new XmlSerializer(typeof(XmlDocument));
                        var objectToParse = (XmlDocument) serializer.Deserialize(reader);
                        var pdfFileLocation = await _service.ParseObject(objectToParse);
    
                        var response = new HttpResponseMessage(HttpStatusCode.OK);
                        var file = System.IO.File.ReadAllBytes(pdfFileLocation);
    
                        response.Content = new ByteArrayContent(file);
                        response.Content.Headers.Add("Content-Type", "application/pdf");
    
                        return response;
                    }
                } catch (Exception e) {
                    return new HttpResponseMessage(HttpStatusCode.BadRequest);
                }
            });
        }
    

    XML文件是一个简单的XML文件,我将其转换为一个对象,该部分起作用,并且与它无关(也是NDA)。

    我看到了几个(不止几个)与我类似的问题,但我什么都试过了,还没有找到解决方案。 通过邮递员,我得到如下回复:

    {
     "version": {
         "major": 1,
         "minor": 1,
         "build": -1,
         "revision": -1,
         "majorRevision": -1,
         "minorRevision": -1
     },
     "content": {
         "headers": [
             {
                 "key": "Content-Type",
                 "value": [
                     "application/pdf"
                 ]
             }
         ]
     },
     "statusCode": 200,
     "reasonPhrase": "OK",
     "headers": [],
     "requestMessage": null,
     "isSuccessStatusCode": true 
    }
    

    如您所见 response.Content 就像什么都没有设置一样。百分之百确定,该文件是在本地创建的,它是一个有效的pdf,我可以打开并查看。

    我尝试了以上多种不同的回答,但都没有效果。要么是406,要么是空内容。有人能帮我吗?过去4个小时我一直在头痛。

    谢谢

    1 回复  |  直到 6 年前
        1
  •  4
  •   Métoule    5 年前

    在ASP中。NET内核中,控制器操作返回的所有内容都是序列化的:不能返回 HttpResponseMessage ,因为它也将被序列化(这是您在PostMan结果中看到的结果)。

    方法的签名应该返回 IActionResult ,然后您应该致电 File method ,例如:

    public async Task<IActionResult> PostMe() {
        try {
            using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) {
                var serializer = new XmlSerializer(typeof(XmlDocument));
                var objectToParse = (XmlDocument) serializer.Deserialize(reader);
                var pdfFileLocation = await _service.ParseObject(objectToParse);
    
                var file = System.IO.File.ReadAllBytes(pdfFileLocation);
    
                // returns a variant of FileResult
                return File(file, "application/pdf", "my_file.pdf");
            }
        } catch (Exception e) {
            return BadRequest();
        }
    }
    

    请注意 文件 方法返回的不同变体 FileResult ,这取决于您使用的重载。