这个问题被问了很多,但即使我尝试了他们提供的解决方案,我仍然会收到错误。
我发送一个以Person对象作为参数的帖子请求,但我得到:
405 - 方法不允许错误“
码:
合同:
[ServiceContract]
public interface IPayMentService
{
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/AddPerson",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
void AddPerson(Person person);
}
[DataContract]
public class Person
{
[DataMember]
public int Id { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public String Name { get; set; }
}
服务:
public class PayMentService : IPayMentService
{
public void AddPerson(Person person)
{
//..logic
}
}
客户:
$(document).ready(function() {
var person = {Id: 1, Age : 13, Name: "zag"};
$.ajax({
url: 'http://localhost:64858/PayMentService.svc/AddPerson',
type: 'POST',
contentType: "application/json",
data: JSON.stringify(person),
dataType: 'json'
})
});
谢谢,
尝试使用global.asax文件中的此代码:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
如果您的Option请求未返回合适的状态,则请求也将失败。要确保选项请求返回200状态,您最好更改状态代码。您还可以在web.config中添加这些标头。
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="*"/>
</customHeaders>
</httpProtocol>
</system.webServer>
protected void Application_EndRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.StatusCode = 200;
}
}
如果您不熟悉跨区域请求,可以参考mdn