好的!這是GET方法,儘管強烈建議不要在查詢字符串中發送用戶名和密碼,但要爲您提供啓動器,您可以使用它。
定義你的合同:
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebGet(UriTemplate = "/username={username}&password={password}",
ResponseFormat = WebMessageFormat.XML,
BodyStyle = WebMessageBodyStyle.Bare)]
string MyMethod(string username, string password);
}
而在你的實現方法,可以檢索相同的用戶名和密碼。
public class MyServiceImpl:IMyService
{
public string MyMethod(string username, string password)
{
return "You entered "+username +" and "+password; // This will returned as an XML.
}
}
更改的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" maxRequestLength="2147483647" executionTimeout="300"/>
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="" name="Namespace.MyService">
<endpoint address="" behaviorConfiguration="RESTBehavior" binding="webHttpBinding"
bindingConfiguration="webHttpBG" contract="Namespace.Name.IMyService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:51855/MyService.svc" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webHttpBG" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647"
maxBufferPoolSize="21474836470" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="RESTBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<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>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http" bindingConfiguration="webHttpBG" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
並進行測試,您可以使用瀏覽器。在Web.Config文件中定義類型url。例如
http://localhost:51855/MyService.svc/username=myname&password=123
當你鍵入瀏覽器這個網址並回車就會打電話給你「的MyMethod」提供服務正在運行。
您也可以使用Fiddler來測試您的服務。
轉到WCF REST。這很容易。 –
嗨Faizan謝謝!我正在使用WCF REST。你能解釋一下如何傳遞用戶名密碼並檢索服務中的相同內容。 – RamKr
感謝您的寶貴意見!我已經成功地在http請求中使用來自客戶端html文件的Ajax/JQuery添加了Authorization標頭,並且還檢索了wcf端的用戶憑證。現在還有一個問題想到,wcf方面有沒有什麼方法可以知道用戶是否沒有提供授權頭並自動發送401,而不是進一步處理請求。 – RamKr