我正在尝试将一些表单数据从我的 angular 6 应用程序发布到我的 web api。但是,我总是收到错误消息“OPTIONS http://localhost:52994/api/Mail/SendMail 405 (Method Not Allowed)”和“Access to XMLHttpRequest at ' http://localhost:52994/api/Mail/SendMail ' from origin ' http://localhost:4200 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。为了清楚起见,我正在编写所有必要的代码,但如果不清楚,请随时询问更多。
角度法:
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;
}
这是目标 web 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>
通过安装 Cors 并启用 Cors 来实现这一点,如下所示:
// Enable CORS for the Angular App
var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(cors);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句