Webapi core 2.1 and jQuery (CORS)

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)
    }
});

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.