我需要在silverlight项目中上传一个文件到远程服务器。
以下是我的代码。我想上传一个PDF文件。
public bool UploadHelpDocument(string FileName, byte[] ms)
{
if (FileName != null)
{
if (ms.Length > 0)
{
FileUpload fu = new FileUpload();
string HelpDocPath = ConfigurationManager.AppSettings["HelpDocs"];
if (!Directory.Exists(HelpDocPath))
{
Directory.CreateDirectory(HelpDocPath);
}
if(fu.saveFileChunk(FileName, ms, HelpDocPath, 0) == true)
{
string fileURL = ConfigurationManager.AppSettings["HelpDocs"] + FileName;
byte[] localHelpfile = readLocalShapeFile(fileURL);
string sURL = "http://serverpath";
WebRequest request = WebRequest.Create(sURL);
request.ContentType = "application/ms-word";
request.Method = "PUT";
request.Credentials = new NetworkCredential("", "");
Stream requestStream = request.GetRequestStream();
requestStream.Write(localHelpfile, 0, localHelpfile.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
return false;
}
}
}
return false;
}
我在上出错WebResponse response=request。GetResponse()这条线。它说远程服务器返回了一个错误:(405)方法不允许
这个错误的原因可能是什么?
感谢
是否要从Silverlight应用程序发送WebRequest?
- 如果没有,我认为目标服务器无法处理这种请求方法或文件类型。您可以尝试更改ContentType,如:
这个:
request.ContentType = "text/msword";
或
request.ContentType = "text/plain";
如果这没有帮助,我认为服务器不处理PUT方法,您需要研究目标服务器的配置。
- 如果是,这看起来像是跨域问题。您可以使用两种方法之一
1) 如果您可以访问目标服务器,您可以在它们上创建crossdomain.xml或/和clientaccesspolicy.xml,如下所示:
clientaccesspolicy.xml
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
crossdomain.xml
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
你可以阅读更多:
https://msdn.microsoft.com/en-us/library/cc197955%28VS.95%29.aspx
http://www.leggetter.co.uk/2008/10/24/how-to-make-a-cross-domain-web-request-with-silverlight-2.html
2) 如果您无法访问目标服务器(更糟糕的消息)。您需要创建绕过本地服务器的WebRequest。最好的方法是将Silverlight与WCF RIA服务集成。首先,您需要通过RIA服务将文件发送到本地服务器,然后从服务器将带有此文件的WebRequest无限发送到目标服务器。
public void RIAHandleFile(byte[] file)
{
//(...)
requestStream.Write(file, 0, file.Length);
//(...)
}
在Silverlight中,像一样调用此函数
byte[] file;
InvokeOperation ria = domainContext.RIAHandleFile(file)