【问题标题】:Why Web Api (.Net Core) always return JSON ignored the value in ContentType?为什么 Web Api (.Net Core) 总是返回 JSON 忽略 ContentType 中的值?
【发布时间】:2017-10-28 18:33:56
【问题描述】:

我有 2 个 Web API,它们具有完全相同的代码和相同的引用。

  • 第一个(称为项目 A)在 .net 4.6 下运行,是旧的 web api 项目
  • 第二个(称为项目 B)也在 .net 4.6 下运行,但它是新的 .Net 核心 web api 项目。

我使用了与下面相同的参考

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using PdfSharp.Drawing;
using PdfSharp.Pdf;

这是他们都使用的代码。

public HttpResponseMessage TestReport()
{
    HttpResponseMessage response;

    PdfDocument document = HelloWorld();

    using (MemoryStream memoryStream = new MemoryStream()) {
        document.Save(memoryStream, false);


        byte[] buffer = memoryStream.GetBuffer();
        var contentLength = buffer.Length;
        response = new HttpResponseMessage(HttpStatusCode.OK);

        // Byte Array Test
        //response.Content = new ByteArrayContent(buffer);
        //response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        //response.Content.Headers.ContentLength = contentLength;
        //response.Content.Headers.ContentDisposition.FileName = "anything.pdf";
        //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");


        //var test = response.Content.ReadAsStreamAsync();

        // Stream Content Test
        response.Content = new StreamContent(new MemoryStream(buffer));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        response.Content.Headers.ContentLength = contentLength;
        ContentDispositionHeaderValue contentDisposition = null;
        if (ContentDispositionHeaderValue.TryParse("attachment; filename=" + "helloWorld" + ".pdf", out contentDisposition)) {
            response.Content.Headers.ContentDisposition = contentDisposition;
        }

        return response;
    };
}

public PdfDocument HelloWorld()
{
    // Create a new PDF document
    PdfDocument document = new PdfDocument();
    document.Info.Title = "Created with PDFsharp";

    // Create an empty page
    PdfPage page = document.AddPage();

    // Get an XGraphics object for drawing
    XGraphics gfx = XGraphics.FromPdfPage(page);

    //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

    // Create a font
    XFont font = new XFont("Times New Roman", 20, XFontStyle.BoldItalic);

    // Draw the text
    gfx.DrawString("Hello, World!", font, XBrushes.Black,
        new XRect(0, 0, page.Width, page.Height),
        XStringFormats.Center);

    // Save the document...
    const string filename = "HelloWorld_tempfile.pdf";
    //document.Save(filename);
    return document;


}

当我调用它们(从另一个控制器或从浏览器)时,它们会产生 2 个不同的结果

  • 项目A返回的Pdf文件正确响应头是application/pdf
  • 无论我在响应标头中设置什么,项目 B 始终返回 Json (application/json) 格式。我尝试过 xml、文本、流、字节数组。没有任何效果。

我的问题是:

  • 到底是怎么回事?又是微软@#%^& 吗?
  • 我能为项目 B 做些什么来返回正确的响应(按照我的定义)

P/S:这是我的 web.config 文件

项目 B:来自模板的默认值(我无法将其粘贴到此处,不知道为什么)

项目 A:来自模板的默认值(我无法将其粘贴到此处,不知道为什么)

【问题讨论】:

  • 您必须发送具有正确值的accept 标头。
  • 请分享来自工作 api 项目的 WebApiConfig.cs
  • 大家好,这是我的 Web.config <?xml version="1.0" encoding="utf-8"?> <configuration> <!-- Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380 --> <system.webServer> <handlers> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/> </handlers> <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/> </system.webServer> </configuration>
  • 对不起,我无法在stackoverflow上格式化xml内容。基本上,我使用了默认的 web.config。没有修改。
  • @Dr.Fre 你介意澄清你的评论吗?我不太确定该怎么做?但为什么我需要在 .netcore(目标 .net 4.6)项目中这样做

标签: c# asp.net-web-api asp.net-web-api2 asp.net-core-webapi


【解决方案1】:

asp.net-core 默认不支持HttpResponseMessage,这是来自以前版本的Web API。 Core 将操作结果中的 HttpResponseMessage 视为模型,并将其序列化为 JSON。

重构项目 B 代码...

public IActionResult TestReport() {        
    var document = HelloWorld();
    using (var memoryStream = new MemoryStream()) {
        document.Save(memoryStream, false);
        var buffer = memoryStream.GetBuffer();
        var contentDisposition = new ContentDispositionHeaderValue("attachment");
        contentDisposition.SetHttpFileName("helloWorld.pdf");
        Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
        return File(buffer, "application/pdf");
    }            
}  

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2019-04-22
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多