[英]400 Bad Request JQuery WCF Service
我在VS2012的ASP.NET 4.5中創建了WCF Web服務,該服務返回JSON響應。 該服務可以與內置的Web服務客戶端正常工作,並且在Web.config文件中正確設置了端點。
在客戶端,我在Jquery中有一個簡單的測試腳本,但是運行該腳本后,會收到一個HTTP / 1.1 400 Bad Request。
Web服務根本不需要任何輸入-因此data:設置為空字符串。
這是調用服務時得到的信息(在FireFox中使用HTTP Live Headers插件)。
http://localhost:58234/CCSVC.svc/Get_BTCE_BTC_USD
OPTIONS /CCSVC.svc/Get_BTCE_BTC_USD HTTP/1.1
Host: localhost:58234
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Origin: http://localhost:59099
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type
Connection: keep-alive
HTTP/1.1 400 Bad Request
Cache-Control: private
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcc2l0ZXMyXENyeXB0b0NvaW5TZXJ2aWNlc1xDQ1NWQy5zdmNcR2V0X0JUQ0VfQlRDX1VTRA==?=
X-Powered-By: ASP.NET
Date: Mon, 23 Dec 2013 16:08:27 GMT
Content-Length: 0
和腳本:
$(document).ready(function () {
$('#btnRefresh').click(function () {
$.ajax({
type: 'GET',
url: 'http://localhost:58234/CCSVC.svc/Get_BTCE_BTC_USD',
data: '',
contentType: 'application/json',
dataType: 'json',
processData: true,
crossDomain: true,
success: function (msg) {
ServiceSucceeded(msg);
},
error: function (msg) {
ServiceFailed(msg);
}
});
function ServiceSucceeded(result) {
alert("success");
};
function ServiceFailed(result) {
alert("fail");
};
});
});
自然,它失敗了。 我嘗試了幾種不同的組合,沒有運氣和POST,還有GET。 crossDomain是/否,processData是/否等。似乎沒有任何作用。
這是Web服務的合同:
<OperationContract()>
<WebInvoke(BodyStyle:=WebMessageBodyStyle.Bare, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function Get_BTCE_BTC_USD() As TradeData
這似乎是請求的問題,但該錯誤並未表明可能是什么。
這是WCF服務中web.config的內部:
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CryptoCoinServices.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<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>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="metadataBehavior" name="CryptoCoinServices.Service1">
<!-- leave address empty for localhost -->
<endpoint
address=""
binding="basicHttpBinding"
contract="CryptoCoinServices.IService1"
/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<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>
建議您在jQuery腳本中進行以下更改(仍然無效,但數據的{}顯然是強制性的):
$.ajax({
type: 'POST',
url: 'http://localhost:58234/CCSVC.svc/Get_BTCE_BTC_USD',
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: true,
crossDomain: true,
success: function (msg) {
ServiceSucceeded(msg);
},
error: function (msg) {
ServiceFailed(msg);
}
});
更改為webHttpBinding之后的新錯誤:
http://localhost:58234/CCSVC.svc/Get_BTCE_BTC_USD
OPTIONS /CCSVC.svc/Get_BTCE_BTC_USD HTTP/1.1
Host: localhost:58234
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Origin: http://localhost:59099
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Length: 513
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcc2l0ZXMyXENyeXB0b0NvaW5TZXJ2aWNlc1xDQ1NWQy5zdmNcR2V0X0JUQ0VfQlRDX1VTRA==?=
X-Powered-By: ASP.NET
Date: Mon, 23 Dec 2013 17:02:44 GMT
由於您正在進行跨域通信,因此默認情況下WCF不支持跨域通信。請查看以下鏈接以獲取完整示例
我創建了一個示例WCF,它可以與您說明的方案一起使用。 但是代碼在c#中。 您可以嘗試以下配置和代碼。
namespace WCF
{
[ServiceContract(Namespace = "Testing")]
//[ServiceContract]
public interface ITestWCF
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
String HelloWorld();
}
}
namespace WCF
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService2" in both code and config file together.
class TestWCF : ITestWCF
{
public string HelloWorld()
{
return "Hello!!!";
}
}
}
Ajax呼叫:
$.ajax({
url: "Service1.svc/rest/HelloWorld?",
type: "POST",
data: "{}",
success: fnsuccesscallback,
contentType: "application/json; charset=utf-8",
error: fnerrorcallback,
dataType: "json"
});
Web.config文件:
<system.serviceModel>
<client />
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="WCF.TestWCF" behaviorConfiguration="TestWCFBehaviour">
<host>
<baseAddresses>
<add baseAddress="http://localhost:1991/Service1.svc"/>
</baseAddresses>
</host>
<endpoint address="rest" binding="webHttpBinding" contract="WCF.ITestWCF" behaviorConfiguration="TestWCFEndPointBehaviour" name="httpEndpoint"></endpoint>
<endpoint address="soap" binding="basicHttpBinding" contract="WCF.ITestWCF" bindingConfiguration="BasicHttpEndpointBinding"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TestWCFBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="TestWCFEndPointBehaviour">
<!--<enableWebScript/>-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
請注意,我已經使用webHttpBinding公開了一個端點,並且將其命名為rest
您也可以參考http://www.wcf.dotnetarchives.com/2013/12/invoking-restful-wcf-service-with_20.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.