你如何在C#中阅读pdf并将文件返回给用户?

时间:2017-09-19 16:52:10

标签: javascript c# asp.net-mvc pdf download

我有一个C#,Kendo MVC,Razor项目。用户单击Kendo网格中的一行,该行触发on change事件,该事件向控制器发出api调用,控制器读取pdf文件,并将其返回给用户进行下载。我用csv文件完成了这个并且它工作正常,但是使用pdfs我得到一个错误。有人能告诉我为什么这段代码不适用于pdfs?

Javascript in View

window.location = "/api/WoApi/GetPDF/1?pdf=" + JSON.stringify(ID);

控制器中的C#

[HttpGet]
public System.Net.WebResponse GetPDF(string pdf)
{
    System.Net.WebRequest request = System.Net.WebRequest.Create("C:\\inetpub\\wwwroot\\Projects\\Attachments\\Invoice_2424.pdf");
    System.Net.WebResponse response = request.GetResponse();

    return response;
}

错误消息

> <Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Net.FileWebResponse' with data contract name 'FileWebResponse:http://schemas.datacontract.org/2004/07/System.Net' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass7.<WriteToStreamAsync>b__6() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
</StackTrace>
</InnerException>
</Error>

**更新#1 **

我得到以下代码来返回文件,但我仍然收到相同的错误消息:

string file = "C:\\inetpub\\wwwroot\\Projects\\Attachments\\Invoice_2424.pdf";
var test = new System.Web.Mvc.FilePathResult(file, "application/pdf");
return test;

错误讯息:

Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Web.Mvc.FilePathResult' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.InvalidDataContractException
</ExceptionType>
<StackTrace>
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.DataContractSerializer.GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass7.<WriteToStreamAsync>b__6() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
</StackTrace>
</InnerException>
</Error>

2 个答案:

答案 0 :(得分:1)

您还可以尝试仅使用正确的mimetype返回指定url的文件。

[HttpGet]
public ActionResult GetPDF(string pdf)
{
    string file = "C:\\inetpub\\wwwroot\\Projects\\Attachments\\Invoice_2424.pdf";

    return File(file, "application/pdf");
}

答案 1 :(得分:-1)

CSV文件可能有效,因为它是基于文本的格式,但pdf不是。

看起来您正在使用网络API,

试试这种方式,

[HttpGet]
public HttpResponseMessage Generate()
{

     var stream = new FileStream("C:\\inetpub\\wwwroot\\Projects\\Attachments\\Invoice_2424.pdf", FileMode.Open);

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.ToArray())
    };
    result.Content.Headers.ContentDisposition =
        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "fileName.pdf"
    };
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");

    return result;
}