asp.net-web-api ASP.NET WEB API CORS Enabling Properly send authenticated request from jQuery against Web API 2 endpoint

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The following example shows how to properly construct both GET and POST requests against Web API 2 (CORS must be configured server-side, if sent from another domain):

<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.js"></script>
CORS with Windows Authentication test
<script type="text/javascript">

    // GET
    $.ajax({
        url: "endpoint url here",
        type: "GET",
        dataType: "json",
            xhrFields: {
            withCredentials: true
        }
    })
    .done(function (data, extra) {
      alert("GET result" + JSON.stringify(data));
    })
    .fail(function(data, extra) {
    });
    
    //POST
    $.ajax({
        url: "url here",
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({testProp: "test value"}),
        xhrFields: {
            withCredentials: true
        },
        success: function(data) { 
            alert("POST success - " + JSON.stringify(data)); 
        }
    })
    .fail(function(data) {
        alert("Post error: " + JSON.stringify(data.data));
    });
    
</script>

Server-side code:

    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("GetRequestUsername")]
    public HttpResponseMessage GetRequestUsername()
    {
        var ret = Request.CreateResponse(
            HttpStatusCode.OK,
            new { Username = SecurityService.GetUsername() });
        return ret;
    }

    [System.Web.Http.HttpPost]
    [System.Web.Http.Route("TestPost")]
    public HttpResponseMessage TestPost([FromBody] object jsonData)
    {
        var ret = Request.CreateResponse(
            HttpStatusCode.OK,
            new { Username = SecurityService.GetUsername() });
        return ret;
    }


Got any asp.net-web-api Question?