具有多个参数{W 44}的WCF Restful API

时间:2016-12-21 12:36:18

标签: vb.net wcf wcf-rest

我正在努力在VB.Net中创建一个WCF restful API,到目前为止,从一个参数获取MSSQL数据库中的数据,并且保存数据当前正在工作。 目前我正在尝试创建一个包含多个参数(电子邮件和密码)的服务合同来验证用户登录。这不断引发以下错误,我无法弄清楚如何解决这个问题:

  

错误:无法从localhost获取元数据:12345 / SMPCService.svc如果这是您有权访问的Windows(R)Communication Foundation服务,请检查您是否已在指定地址启用元数据发布。有关启用元数据发布的帮助,请参阅go.microsoft.com/fwlink/?LinkId=65455上的MSDN文档.WS-Metadata Exchange错误URI:localhost:12345 / SMPCService.svc元数据包含无法解析的引用:localhost :12345 / SMPCService.svc”。无法激活请求的服务“localhost:12345 / SMPCService.svc”。有关详细信息,请参阅服务器的诊断跟踪日志.HTTP GET错误URI:localhost:12345 / SMPCService.svc下载'/localhost:12345/SMPCService.svc'时出错。请求失败,并显示错误消息: -

这是我的服务合同:

<OperationContract()>
<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="ValidateLogin/{e}/{p}")>
Function ValidateLogin(ByVal sEmailAddress As String, ByVal sPassword As String) As List(Of CheckLogin)

这是名为ValidateLogin的函数:

Public Function ValidateLogin(ByVal sEmailAddress As String, ByVal sPassword As String) As List(Of CheckLogin) Implements ISMPCService.ValidateLogin
    Dim result As List(Of CheckLogin) = New List(Of CheckLogin)
    Dim uAction = New CheckLogin
    Dim pwd As String = ""
    Try
        ' Dimension Local Variables
        Dim uRecSnap As ADODB.Recordset

        ' Check For Open Connection
        If uDBase Is Nothing Then
            OpenConnection()
            bConnection = True
        End If

        ' Run Stored Procedure - Load Timesheet Record
        uCommand = New ADODB.Command
        With uCommand
            .ActiveConnection = uDBase
            .CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
            .CommandTimeout = 0
            .Parameters.Append(.CreateParameter("@EmailAddress", ADODB.DataTypeEnum.adVarChar, ADODB.ParameterDirectionEnum.adParamInput, 30, sEmailAddress))
            .CommandText = "API_WebUser_ValidateLogin"
            uRecSnap = .Execute
        End With

        ' Populate List
        Do Until uRecSnap.EOF
            pwd = If(IsDBNull(uRecSnap("UserPassword").Value), "", uRecSnap("UserPassword").Value)
            uRecSnap.MoveNext()
        Loop
        uRecSnap = Nothing

        If pwd <> "" Then
            If pwd.Substring(0, 4) = "$2y$" Then
                Mid(pwd, 3, 1) = "a"
            End If

            If BCrypt.Net.BCrypt.Verify(SHA512Hash(sPassword), pwd) Then
                uAction.WasSuccessful = "OK"
                uAction.StatusDescription = "User credentials match"
            Else
                uAction.WasSuccessful = "FAIL"
                uAction.StatusDescription = "Failed to authorize user"
            End If

        Else
            uAction.WasSuccessful = "FAIL"
            uAction.StatusDescription = "Failed to authorize user"
        End If

        result.Add(uAction)
    Catch ex As Exception
        ' Catch Error
        If Err.Number <> 0 Then
            Console.WriteLine(ex.Message)
        End If

    Finally
        ' CleanUp

        ' Close Database Connection
        If bConnection Then CloseConnection()

    End Try

    Return result
End Function

最后,这是我的Web.config:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <!--Disabled custom errors to allow display of detailed errors.-->
    <customErrors mode="Off"/>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" relaxedUrlToFileSystemMapping="true"/>
  </system.web>
  <system.serviceModel>
    <services>
      <!--Specify services the application hosts. 
      Name specifies the type that provides an implementation of a service contract.
      Behavior Configuration specifies the name of one of the behaviours found in the behaviours element and governs actions such as whether the service allows impersonation.-->
      <service name="SMPCWebService.SMPCService" behaviorConfiguration="SMPCWebService.SMPCServiceBehaviour">
        <!--Define the service endpoints.-->  
        <endpoint address="../SMPCService.svc" behaviorConfiguration="webBehaviour" binding="webHttpBinding" contract="SMPCWebService.ISMPCService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
          <behavior name="SMPCWebService.SMPCServiceBehaviour">
            <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
            <serviceMetadata httpGetEnabled="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>
      <!--Define the endpoint behaviour.-->
      <endpointBehaviors>
        <behavior name="webBehaviour">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <!-- Allowing Cross-Origin Resource Sharing (CORS) - The httpProtocol settings allow web services to be called from external domains using JavaScript-->
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>
    <modules runAllManagedModulesForAllRequests="true"/>
    <httpErrors errorMode="Detailed" />
    <validation validateIntegratedModeConfiguration="false"/>
    <!--
        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>

</configuration>

我已经查看了许多帖子以找到这个问题的提示,但我没有到达任何地方。

我看过的帖子:

Why do I get this WCF error when 'GET'ing?

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

How to send email address as parameter in wcf method

http://jeffbarnes.net/blog/post/2006/10/16/metadata-exchange-endpoint.aspx

1 个答案:

答案 0 :(得分:0)

在尝试了不同的方法之后,我终于解决了我出错的地方。

函数的参数名称需要与UriTemplate中指定的参数命名相同。

原件:

<OperationContract()>
<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="ValidateLogin/{e}/{p}")>
Function ValidateLogin(ByVal sEmailAddress As String, ByVal sPassword As String) As List(Of CheckLogin)

修正:

<OperationContract()>
<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="ValidateLogin/{e}/{p}")>
Function ValidateLogin(ByVal e As String, ByVal p As String) As List(Of CheckLogin)
相关问题