我有一种OperationContract
方法,我试图查询并将数据插入数据库。我正在使用一种POST
方法并从浏览器中的 javascript 调用该服务。WCF 服务在同一个域中,所以我不应该使用JSONP
. 我也在修改数据,所以它应该是POST
请求而不是GET
请求。但是我仍然收到“方法不允许错误”。有没有人遇到过这种情况?
我的服务正在调用
http://some_url.com/services/ProfileService.svc/json/CurrentUser
奇怪的是,GET
即使我指定了一个POST
. 但是,在页面加载时,它似乎正在尝试POST
请求。
访问 url 时的浏览器响应:
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>