这个问题经常问很多,但是即使我尝试了他们提供的解决方案,我仍然会遇到错误。
我正在以某人对象作为参数发送邮政请求,但我得到:
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();
}
}
如果您的选项请求不返回合适的状态,则该请求也将失败。为了确保期权请求返回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
https://developer.mozilla.org/en-us/docs/web/http/cors