gpt4 book ai didi

c# - 无法打开主机 WCF REST 服务

转载 作者:太空宇宙 更新时间:2023-11-03 16:46:40 26 4
gpt4 key购买 nike

我正在尝试实现一些 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(); 我得到:

The remote server returned an error: (400) Bad Request.

我应该怎么做才能解决这个问题?

最佳答案

您正在从托管服务的同一进程发出服务请求。我认为它们应该是分开的,例如您的服务主机在控制台应用程序中,您的测试在另一个应用程序中。

关于c# - 无法打开主机 WCF REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5714751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com