我已经看到了很多有关此的帖子,但是似乎无法真正找到答案。
[免责声明:我对WCF不太了解-尽管我可以访问代码,但这是我要连接的现有项目。]
我已经创建了一个html / javascript客户端来访问现有的WCF服务API。每个都是独立的应用程序,因此当我在本地运行时,客户端和服务器都在localhost
上运行,但是端口号不同。这有效。客户端应用程序可以通过以下呼叫来调用WCF服务:https://localhost:4435/sessions.svc/getsession?sessionPK=3
。
当我将两个应用程序都安装在服务器上(两者都与不同的虚拟应用程序在同一台服务器上运行)时,该服务确实正在运行-我可以从网络浏览器中访问https://myserver.com/api/sessions.svc
,然后返回页面该服务告诉我它可以正常工作。
但是,现在,当客户端尝试以与本地相同的方式访问服务(https://myserver.com/api/sessions.svc/getsession?sessionPK=3
)时,出现404 Not Found错误。
客户端和WCF服务都托管在具有相同根域的同一台服务器上-因此,CORS应该不会成为问题。
以下是一些代码段:
** WCF服务**
[ServiceContract]
public interface ISessions
{
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
string GetSession(int? sessionPK);
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Sessions : BaseService, ISessions
{
public string GetSession(int sessionPK)
{
...
}
}
**服务的Web.Config **
<service behaviorConfiguration="BehaviorConfig" name="Sessions">
<endpoint address="" binding="webHttpBinding" behaviorConfiguration="json" contract="ISessions">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
**客户**
export class DataService {
constructor(private http : HttpClient){
this.http.configure(config => {
config.withBaseUrl("https://myserver.com/api/");
config.withHeader("Accept", "application/json");
config.withHeader("Content-Type", "application/json");
config.withCredentials(true);
})
}
public async getSessionById(id : number = 0){
try{
let result = this.http.get(`sessions.svc/getsession?sessionPK=${id}`);
if(!result.isSuccess)
throw response;
...
}
catch(error : any){
...
}
}
更新
在回应Peter时,我从https://myserver.com/api/sessions.svc
得到的响应与从https://myserver.com/api/sessions.svc?wsdl
得到的响应相同。这是一个这样的页面:
该服务似乎没有返回它公开的操作的列表。顺便说一下,它在localhost
上的执行方式完全相同。
答案 0 :(得分:0)
如果CORS没问题,则访问服务的URI或格式可能有误。您可以在服务中打开帮助文档,以了解如何请求界面:
<endpointBehaviors>
<behavior name="ESEndPointBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
访问帮助文档:
这是服务接口的设计:
[OperationContract]
[WebGet(UriTemplate = "user/?name={name}",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Result GetUserData(string name);
我没有将bodystyle设置为WebMessageBodyStyle.Wrapped因为WebMessageBodyStyle.Wrapped主要用于封装主体,但是get方法中没有主体。并且将“ WebMessageBodyStyle.Wrapped”设置为帮助文档将不会生成正确的请求格式,如下所示:
常规帮助文档应如下所示:
它包含请求的URI和格式。
答案 1 :(得分:0)
结果是,我在本地运行HTTP,在服务器上运行HTTPS。我通过添加以下内容解决了我的问题:
<webHttpBinding>
<binding>
<security mode="Transport"></security>
</binding>
</webHttpBinding>