ajax post 请求报错Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' heade

时间:2023-11-23 21:04:44

jquery ajax跨域请求,webapi webconfig配置

前台代码(放了一部分)

function CheckIn(roomno) {
$.ajax({
url: 'https://www..../RoomAssign',
type: 'post',
async: false,
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: JSON.stringify({
AccountId: localStorage.getItem("Accountid"),
Address: localStorage.getItem("Address"),
ArrivalDate: localStorage.getItem("Arrivaldate"),
Birthday: localStorage.getItem("Birthday"),
CertificateNo: localStorage.getItem("Certificateno"),
CertificateType: localStorage.getItem("Certificatetype"),
Country: localStorage.getItem("Country"),
})

后台代码:

  public List<RoomAssign> RoomASSign([FromBody] RoomAssignIn model)
{
try
{
RoomAssignReq req = new RoomAssignReq();
req.AccountId = model.Accountid;
req.RoomNo = model.Roomno;
req.Rsvno = model.Rsvno;
RoomAssignRsp rsp = null;
ErrorInfo error = null;
List<RoomAssign> Rd = new List<RoomAssign>();
RoomAssign list = new RoomAssign();
if (db.RoomAssign(req, ref rsp, ref error) == )
{
list.resultcode = rsp.ResultCode;
list.description = rsp.Description; }
else
{
list.description = error.ErrorMessage;
}
Rd.Add(list);
return Rd;
}
catch (Exception ex)
{
throw ex;
} }

web配置以下内容

<system.web>
<!--提供Web服务访问方式-->
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
</system.web> <configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<modules>
<add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/>
</modules>
</system.webServer>
</configuration>

如果报错:

未能加载类型“WebServiceDemo.MyHttpModule”。去掉

 <modules>
<add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/>
</modules>

如果想选定的网站可能跨域访问,修改配置如下:

<add name="Access-Control-Allow-Origin" value="http://www....." />