我正在尝试将一些表格数据从我的angular 6应用发布到我的网络api。但是,我总是收到一条错误消息“ OPTIONS http://localhost:52994/api/Mail/SendMail 405(不允许使用方法)”和“从来源“ http://localhost:52994/api/Mail/SendMail”到“ http://localhost:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。为了清楚起见,我正在编写所有必要的代码,但是如果不清楚,可以随时询问更多。
角度方法:
sendMail(mail:Mail) {
console.log(mail); // prints desired data
this.http.post('http://localhost:52994/api/Mail/SendMail',mail)
.subscribe(
data => { console.log ("POST was successful",data)},
error => { console.log("Error",error)}
);
}
其中的邮件模型如下:
export class Mail {
Name: string;
Email: string;
Message: string;
To: string;
From: string;
}
这是目标网络api方法:
[HttpPost]
public HttpResponseMessage SendMail([FromBody]MailModel mail)
{
try
{
using (MailMessage mm = new MailMessage(mail.From, mail.To))
{
mm.Subject = "ContactUs";
string body = "You've got a message as below :";
body += "<br /><br />Name : " + mail.Name;
body += "<br /><br />Email : " + mail.Email;
body += "<br /><br />Message : " + mail.Message;
mm.Body = body;
mm.IsBodyHtml = true;
....
smtp.Send(mm);
return Request.CreateResponse(HttpStatusCode.OK, mail);
}
}
catch(Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
模型类:
public class MailModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Message { get; set; }
public string To { get; set; }
public string From { get; set; }
}
我已经在web.config文件中设置了所有必需的标头,如下所示:
<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,OPTION" />
</customHeaders>
</httpProtocol>
答案 0 :(得分:0)
尝试将OPTION
更改为OPTIONS
,以允许使用preflight requests。这些请求将HTTP OPTIONS
method与“ S”一起使用。
<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>
希望有帮助!
答案 1 :(得分:0)
通过安装Cors并启用如下所示的Cors来完成此工作:
// Enable CORS for the Angular App
var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(cors);