I’ve written before about Cordova, AngularJs, WebApi and CORS. (Cross Origin Resource Sharing) Now we have te same hurdle to take with our dotnet core 2.1 webapi.

Since the webapi is on a webserver and accessible to third parties we decided to keep the access fine grained. We will only allow CORS for GET operations on 1 resource. This can be achieved with policies. Below is the dotnet code to add the policy and use it only on the GET operation.
// add this to ConfigureServices
services.AddCors(o => {
o.AddPolicy("AllowGet", builder => {
builder.AllowAnyOrigin() // allow everybody
.WithMethods("GET") // only allow GET
.AllowAnyHeader() // enable preflight
.AllowCredentials(); // needed for auth
});
});
// in the controller
[HttpGet]
[EnableCors(PolicyName = "AllowGet")]
public async Task<IActionResult> Get() {
var result = "your data";
return Ok( result );
}
Now that the webapi supports CORS we can call the GET from our page with jQuery.
$.ajax({
type: "GET",
url: url,
crossDomain: true,
cache: false,
// needed for preflight
xhrFields: {
// needed for auth
withCredentials: true
},
success: function (response) {
// do something with response
},
error: function (response, status, error) {
console.write(error)
}
});