我正在尝试从ajax调用中调用WCF服务。这是我的ajax电话:
$j.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
context: this,
async: false,
url: appServicePath + "Student/GetRolesByUserId",
data: JSON.stringify({ "userId": userId }),
success: this.getRolesByIdResponse,
error: this.getRolesByIdFailure
}
);
当我使用Fiddler测试服务时,我可以从ajax传递其值来获得用户的角色,但是当我从应用程序中调用该服务时,我得到一个错误:405 Method Not Allowed。 我在做什么错了?
答案 0 :(得分:0)
According to your description, I think this problem is due to cross-domain, the problem generates an OPTIONS request, So the method is not allowed. If you put the script in the same domain as the webservice, you won't have this problem.
Here is Http 405 method document.
https://tools.ietf.org/html/rfc7231#section-6.5.5
You now need to turn on cross-domain support for a WCF application hosted on the web server side.
Web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="content-type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Headers.AllKeys.Contains("Origin")&&Request.HttpMethod=="OPTIONS")
{
Response.End();
}
}
Feel free to contact me if you have any questions.