gpt4 book ai didi

c# - WCF Restful Web 服务端点公开但方法都返回 http 404 未找到 c#

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:10 24 4
gpt4 key购买 nike

我已经编写了我的第一个 Web 服务,当我在我的本地开发机器上从 visual studio 测试运行它时,一切都按预期工作。我去客户端部署服务,发现部署后我可以到达端点,但我的所有方法都返回 HTTP 404 not found。

Web 服务是使用 WCF 在 Visual Studio 中编写的,并设置为返回 Json。 Web 服务的目标是 .Net framework 4.5。该站点配置为使用 HTTPS 协议(protocol)并具有有效的 SSL 证书。我已经使用最新版本的 .Net framework 4.5 更新了服务器,并相应地向站点应用了一个应用程序池。

当我从外部浏览器转到客户端服务器上的端点位置时(我修改了屏幕截图和链接以删除真实域):

链接看起来像这样:

https://www.somedomain.co.uk/WorksWebService/WorksWebService.svc

我得到的页面显示了指向 WSDL 和 SingleWSDL 页面的 Web 服务链接,它们正确地显示了端点方法和各种其他配置信息。

Works Web Service Endpoint

在我看来,一切都符合预期,但我有点不确定下一步该去哪里寻找问题。

现在我很不确定 Web.config 文件的要求是什么。下面是 Web 服务的当前 Web.config 文件。可能是我在这里遗漏了有关服务部署的重要信息,但想知道为什么服务在 Visual Studio 中成功运行?唯一需要注意的区别是,在 visual studio 中,我使用 http 而不是 https 运行服务。

<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<connectionStrings>
<add name="BAXISQL"
connectionString="Database=SomeDatabase;Server=SomeServer;User ID=user;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
<system.serviceModel>
<services>
<service name="WorksWebService.WorksWebService">
<endpoint address="" behaviorConfiguration="restful" binding="webHttpBinding"
contract="WorksWebService.IWorksWebService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restful">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
<startup>
<supportedRuntime version="4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

我想我的问题来自 Web.config 文件或我的服务接口(interface)和方法声明中缺少的一些元数据。

以下代码显示了我的接口(interface)(修改后只包含一个方法):

using System.IO;
using System.ServiceModel;
using System.Web.Services;

namespace WorksWebService
{
[ServiceContract]
interface IWorksWebService
{
[OperationContract]
[WebMethod]
string GetTrainingStatus(string urn, string pastdays, string futuredays);
}
}

下面是WebService.svc.cs文件中相应的方法调用(也修改为仅显示单个方法):

using System;
using System.Collections.Generic;
using System.Collections;
using System.Data.SqlClient;
using System.Net;
using System.ServiceModel.Web;
using System.Web;
using Newtonsoft.Json;
using System.Runtime.Serialization;
using System.IO;
using System.ServiceModel;
using System.Text;
using Newtonsoft.Json.Linq;

namespace WorksWebService
{
public class WorksWebService: IWorksWebService
{
// key that all methods must receive in the header to validate that the request is from a valid source
private string baxiSMSKey = "C5A75B32-5BC9-4D89-AB78-F8FE0CF58806";
//BAXI_SMS_KEY: C5A75B32-5BC9-4D89-AB78-F8FE0CF58806

#region TrainingStatus

// test url string
// WorksWebService.svc/rest/member/C211292/trainingstatus?country=GB
/// <summary>
/// Method to find the training status dates for a specific Customer
/// </summary>
/// <param name="urn"></param>
/// <param name="country"></param>
/// <returns>Last valid training status date or future date the customer will be attending training</returns>
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json
, UriTemplate = "rest/member/{urn}/trainingstatus?pastdays={pastdays}&futuredays={futuredays}")]
public string GetTrainingStatus(string urn, string pastdays, string futuredays)
{
string dateString = string.Empty;
WebOperationContext context = WebOperationContext.Current;
// check the headers for the BAXI_SMS_KEY
if (CheckAPIKey())
{
// validate the url parameters
if (ValidateURLStringParameters_GetTrainingStatus(urn, pastdays, futuredays))
{
// find the training status
dateString = GetTrainingDate(urn, pastdays, futuredays);

if (dateString.Contains("Error: "))
context.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; // HTTP Code 500
else if (dateString.Equals(string.Empty))
context.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; // HTTP Code 404
else
context.OutgoingResponse.StatusCode = HttpStatusCode.OK; // HTTP Code 200
}
else
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; // HTTP Code 400
}
else
context.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; // HTTP Code 403

return dateString;
}

/// <summary>
/// method to validate the parameters for GetTrainingStatus Web method
/// </summary>
/// <param name="urn"></param>
/// <param name="pastdays"></param>
/// <param name="futuredays"></param>
/// <returns>True or False</returns>
private bool ValidateURLStringParameters_GetTrainingStatus(string urn, string pastdays, string futuredays)
{
if (string.IsNullOrWhiteSpace(urn))
return false;

if (string.IsNullOrWhiteSpace(pastdays))
return false;

if (string.IsNullOrWhiteSpace(futuredays))
return false;

try
{
Convert.ToInt32(pastdays);
Convert.ToInt32(futuredays);
}
catch (Exception e)
{
return false;
}

return true;
}

/// <summary>
/// Method to find the training status of the member
/// </summary>
/// <param name="urn"></param>
/// <returns>the date of the users training past of future</returns>
private string GetTrainingDate(string urn, string pastdays, string futuredays)
{
string dateSt = string.Empty;
try
{
// first search against customers
var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BAXISQL"].ConnectionString);
connection.Open();
var sqlCommand = connection.CreateCommand();
sqlCommand.CommandText = "SELECT dbo.WORKS_GetTrainingDate_fn(@URN, @Past, @Future)";
sqlCommand.Parameters.AddWithValue("@URN", urn);
sqlCommand.Parameters.AddWithValue("@Past", pastdays);
sqlCommand.Parameters.AddWithValue("@Future", futuredays);

string date = sqlCommand.ExecuteScalar().ToString();
connection.Close();

if (!string.IsNullOrWhiteSpace(date))
{
string[] parts = date.ToString().Split('/');
dateSt = parts[2] + parts[1] + parts[0];
}
}
catch (Exception e)
{
dateSt = "Error: " + e.Message + "<br />Source: " + e.Source + "<br />Stacktrace: " + e.StackTrace;
}

return dateSt;
}

#endregion

#region Private Methods

/// <summary>
/// Method to determine if the API key has been passed in succesfully
/// </summary>
/// <returns>true or false</returns>
private bool CheckAPIKey()
{
bool matchedKey = false;
IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
WebHeaderCollection headers = request.Headers;

System.Diagnostics.Debug.Write("\r\n-------------------------------------------------------");
System.Diagnostics.Debug.Write("\r\n" + request.Method + " " + request.UriTemplateMatch.RequestUri.AbsolutePath);
foreach (string headerName in headers.AllKeys)
{
System.Diagnostics.Debug.Write("\r\n" + headerName + ": " + headers[headerName]);
if (headerName.Equals("BAXI_SMS_KEY"))
{
if (baxiSMSKey.ToString().ToUpper().Equals(headers[headerName]))
{
matchedKey = true;
}
}
}
System.Diagnostics.Debug.Write("\r\n-------------------------------------------------------");

return matchedKey;
}

#endregion

}
}

当我尝试使用 Fiddler 和浏览器访问服务方法时,会出现这些 404 消息。在允许正在构建 Web 门户的第 3 方作为 Web 服务的客户端访问之前,我想证明这些方法工作正常。

如有任何意见或建议,我们将不胜感激。

提前致谢伊恩

最佳答案

在与一些同事进行搜索和讨论后,我找到了解决方案。我怀疑我的 web.config 文件中缺少一些部分。

我没有为 http 和 https 添加端点声明。

<services>
<service name="WorksWebService.WorksWebService">
<endpoint address="" behaviorConfiguration="restful" binding="webHttpBinding" bindingConfiguration="HttpBinding"
contract="WorksWebService.IWorksWebService" />
<endpoint address="" behaviorConfiguration="restful" binding="webHttpBinding" bindingConfiguration="HttpsBinding"
contract="WorksWebService.IWorksWebService" />
</service>
</services>

我还错过了定义安全性和所需凭证类型所需的相关绑定(bind)部分。

<bindings>
<webHttpBinding>
<binding name="HttpBinding">
<security mode="None">
<transport clientCredentialType="None"/>
</security>
</binding>
<binding name="HttpsBinding">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</webHttpBinding>
</bindings>

现在我的 web.config 文件看起来像这样:

<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<connectionStrings>
<add name="BAXISQL" connectionString="Database=SomeDatabase;Server=SomeServer;User ID=User;Password=Password" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.serviceModel>
<services>
<service name="WorksWebService.WorksWebService">
<endpoint address="" behaviorConfiguration="restful" binding="webHttpBinding" bindingConfiguration="HttpBinding"
contract="WorksWebService.IWorksWebService" />
<endpoint address="" behaviorConfiguration="restful" binding="webHttpBinding" bindingConfiguration="HttpsBinding"
contract="WorksWebService.IWorksWebService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restful">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<bindings>
<webHttpBinding>
<binding name="HttpBinding">
<security mode="None">
<transport clientCredentialType="None"/>
</security>
</binding>
<binding name="HttpsBinding">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
<startup>
<supportedRuntime version="4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

我希望这对遇到类似问题的其他人有所帮助。

问候,

漫画程序员

关于c# - WCF Restful Web 服务端点公开但方法都返回 http 404 未找到 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876575/

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