I am trying to send a POST
and GET
requests from angular to .Net web api project GET requests works fine but when it comes to POST
request it doesn't works it gives me following error ,
OPTIONS http://localhost:2073/api/MyAttendance/GetEvent 405 (Method Not Allowed) Access to XMLHttpRequest at ' http://localhost:2073/api/MyAttendance/GetEvent ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Bellow is my POST
request,
In component.ts
getDate() {
let dateList: any = {};
dateList.startDate = this.startDate;
dateList.endDate = this.endDate;
this._lkassetsService.getEventDetails(JSON.stringify(dateList)).subscribe((eventData: any) => {
this.msg = eventData;
});
}
In service.ts
getEventDetails(dateList: any): Observable<any> {
return this._http.post('http://localhost:2073/api/MyAttendance/GetEvent', dateList, {
headers:new HttpHeaders({
'Content-Type': 'application/json'
})
});
}
Bellow is my .net web api request from backend
[HttpPost]
[Route("api/MyAttendance/GetEvent")]
public string Event([FromBody]object Text)
{
return "Success";
}
This request worked fine with postman and in my web.cong
file(.net web api) I have added bellow code,
<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>
And also if I use 'Content-Type': 'application/x-www-form-urlencoded'
instead of 'Content-Type': 'application/json'
It worked fine but output would be null but I want out as json
format
I have no idea about this problem I am very much appreciated If someone can help me. I saw many solutions but that did not work
do not use the action name GetEvent
use other than get
for post method. if you use get in action name it becomes get method
I faced this issue in my project. The way how I succeeded was by doing these changes on API side. (our .net framework version is 4.6.1)
in web.config
<appSettings>
<add key="Cors-Origins" value="http://localhost:4200" />
</appSettings>
in WebApiConfig.cs:
string origins = ConfigurationManager.AppSettings["Cors-Origins"];
config.EnableCors(new EnableCorsAttribute(origins, "*", "*") {SupportsCredentials = true});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.