6
我有一個OperationContract
方法,我試圖查詢和插入數據到數據庫中。我正在使用POST
方法並在瀏覽器中從JavaScript調用服務。 WCF服務位於相同的域中,因此我不必使用JSONP
。我也在修改數據,所以它應該是POST
請求而不是GET
請求。但是,我仍然收到「方法不允許的錯誤」。有沒有人遇到過這種情況?WCF WebInvoke POST - 方法不允許錯誤
我的服務被稱爲在
http://some_url.com/services/ProfileService.svc/json/CurrentUser
奇怪的是,似乎通過GET
請求被稱爲當我去這個網址,即使我specifiy一個POST
。然而,在頁面加載時,它似乎在嘗試POST
請求。要
瀏覽器響應時的網址:
Request URL:http://some_url.com/services/ProfileService.svc/json/CurrentUser
Request Method:GET
Status Code:405 Method Not Allowed
Request Headersview parsed
GET /services/ProfileService.svc/json/CurrentUser HTTP/1.1
這裏是我的方法,我試圖調用:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)]
public HIPUser GetCurrentUser()
{
string[] domainUser;
string Auth_User = HttpContext.Current.User.Identity.Name.ToString().ToLower();
domainUser = Auth_User.Split('\\');
string user = domainUser[1];
Debug.WriteLine(user);
ProfileManager pm = new ProfileManager();
var results = pm.GetUserByUserName(user);
if (results.Length > 0)
{
return results.First();
}
else
{
Debug.WriteLine("IS NULL");
var x = pm.CreateUser(user, null, null);
Debug.WriteLine(x.UserName);
return x;
}
}
客戶:
function getCurrentUser() {
$.ajax({
type: "POST",
url: "services/ProfileService.svc/json/GetCurrentUser",
contentType: "application/json; charset=utf-8",
data: null,
dataType: "json",
error: function (request, error, u) {
alert('blargherror: ' + error);
},
success: function (result, status) {
alert(result.d);
}
});
}
不知道是否需要但是Web.Config
:
<behaviors>
<endpointBehaviors>
<behavior name="jsonBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="metaBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment
aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="ProfileService" behaviorConfiguration="metaBehavior">
<endpoint address="/json"
behaviorConfiguration="jsonBehavior"
binding="webHttpBinding"
bindingConfiguration="secure"
contract="ProfileService" />
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="secure"
contract="ProfileService" />
</service>
</services>
編輯到Web.config中 - 添加綁定
<bindings>
<webHttpBinding>
<binding name="secure">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="secure">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
這不會解決您的問題,但將''{}「'作爲數據傳遞而不是null是個好習慣(http://encosia.com/3-mistakes-to-avoid-when-using-jquery -with-aspnet-ajax /) – Jupaol 2012-07-10 18:52:52
感謝您的文章! – jocey 2012-07-10 19:22:36
我找不到你的代碼有什麼問題,我只是用相同的配置創建了一個類似的服務,它的工作正常,唯一的區別是'bindingConfiguration ='secure'',我想你沒有爲安全原因發佈綁定,以及如果你可以發佈它會很有用。您是否嘗試刪除綁定配置並查看您是否可以訪問您的服務? – Jupaol 2012-07-10 19:32:14