【问题标题】:Web API OWIN receives null data from $.AJAX POST withCredentials:trueWeb API OWIN 从 $.AJAX POST withCredentials:true 接收空数据
【发布时间】:2017-09-10 22:40:44
【问题描述】:

我正在通过 OWIN 调用托管在 Windows 服务上的 Web API,并使用来自 ASP.NET MVC 应用程序的 jquery ajax 发布(通过“数据”选项发布数据)。在我决定添加集成的 Windows 身份验证之前,它一直在工作。我在 $.ajax 调用中添加了 xhrFields: { withCredentials: true } 以完成客户端的身份验证。现在返回的数据为空。

这是我的服务器端启动:

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

这里是 Web API 方法:

public HttpResponseMessage PostSomething([FromBody]string dataIn)

仅供参考,字符串可能太大而无法通过 URI 传递。

这里是 $.ajax 调用:

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

dataIn 始终为空。

【问题讨论】:

    标签: jquery ajax post asp.net-web-api windows-authentication


    【解决方案1】:

    嗯,我找到了答案,这很简单,但我仍然不知道幕后的细节,为什么会这样。只需将“data:'test'”修改为“data:{'':'test'}”即可。

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

    如果有人知道原因,请回复。谢谢!

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多