user2769898
user2769898

Reputation:

Web API OWIN receives null data from $.AJAX POST withCredentials:true

I'm calling a Web API hosted on a Windows Service via OWIN, with a jquery ajax post from an ASP.NET MVC application (posting data via 'data' option). It was working until I decided to add integrated Windows authentication. I added xhrFields: { withCredentials: true } to the $.ajax call to complete the client side of authentication. Now the data returned is null.

Here is my server side Startup:

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();

        var listener =
            (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
        listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

        //Maps Http routes based on attributes
        config.MapHttpAttributeRoutes();
        config.Filters.Add(new AuthorizeAttribute());

        //Enable WebApi
        var cors = new EnableCorsAttribute("*", "*", "*");
        cors.SupportsCredentials = true;
        config.EnableCors(cors);

        appBuilder.UseWebApi(config);
    }
}

Here is the Web API method:

public HttpResponseMessage PostSomething([FromBody]string dataIn)

FYI, the string can be too large to be passed on the URI.

Here is the $.ajax call:

    function TestAjax() {
        $.ajax({
            url: 'http://localhost:8080/api/Test/PostSomething',
            xhrFields: { withCredentials: true },
            type: 'post',
            data: 'test'
        }).done(function (response) {
            alert(response);
        });
    }

dataIn is always null.

Upvotes: 2

Views: 341

Answers (1)

user2769898
user2769898

Reputation:

Well I found the answer, which is simple but I still don't know the details behind the scenes as to why this works. Simply modifying "data: 'test'" to be "data: {'': 'test'}".

function TestAjax() {
    $.ajax({
        url: 'http://localhost:8080/api/Test/PostSomething',
        xhrFields: { withCredentials: true },
        type: 'post',
        data: { '': 'test' }
    }).done(function (response) {
        alert(response);
    });
}

If anyone knows why, please post a reply. Thanks!

Upvotes: 0

Related Questions