【发布时间】:2011-04-19 10:08:10
【问题描述】:
我正在尝试实现一些 WCF 和 REST 服务以在我的服务器上上传文件,我找到了一些我正在尝试实现的代码,但还没有成功。
我的代码
class Program
{
static void Main(string[] args)
{
string address = "http://localhost/UploadService/UploadService.svc/UploadFile/theFile.txt";
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "POST";
req.ContentType = "text/plain";
Stream reqStream = req.GetRequestStream();
string fileContents = "the quick brown fox jumped over the lazy dog.";
byte[] bodyContents = Encoding.UTF8.GetBytes(fileContents);
reqStream.Write(bodyContents, 0, bodyContents.Length);
reqStream.Close();
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
resp = (HttpWebResponse)e.Response;
}
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
}
}
public class UploadService : IUploadService
{
#region IUploadService Members
public void UploadFile(string fileName, Stream fileContent)
{
using (StreamReader fileContentReader = new StreamReader(fileContent))
{
string content = fileContentReader.ReadToEnd();
File.WriteAllText(Path.Combine(@"c:\temp", fileName), content);
}
}
#endregion
}
[ServiceContract]
public interface IUploadService
{
[OperationContract]
[WebInvoke(UriTemplate = "UploadFile/{fileName}")]
void UploadFile(string fileName, Stream fileContent);
}
Web.Config
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="UploadService">
<endpoint address="" binding="webHttpBinding" contract="IUploadService" behaviorConfiguration="RestBehavior">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug httpHelpPageEnabled="false" includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="RestBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
目前,在回复resp = (HttpWebResponse)req.GetResponse();我得到:
远程服务器返回错误:(400) Bad Request。
我应该怎么做才能解决这个问题?
【问题讨论】:
-
在命令提示符下尝试
netstat -ano以查看其他应用程序是什么:查找TCP 127.0.0.1:1157然后在任务管理器中查找进程 ID(右侧列)(ctrl-shift-escape ; 您可能需要查看列,添加进程 ID) -
它被列为监听。我认为这不是端口的问题,而是代码本身的问题,因为我更改了 url 但仍然是同样的错误
-
好的,但根本不应该列出它:如果您的代码当时没有运行,那么其他人正在侦听该端口,这会阻止您。除非我理解错了?但我完全可以相信这是其他 WCF 问题。
-
好的,我停止了应用程序,现在没有列表,但我仍然收到相同的消息:(
-
当我停止本地主机时,我收到以下错误远程服务器返回错误:(400)错误请求。在响应中