我正在通过 OWIN 调用托管在 Windows 服务上的 Web API,并使用来自 ASP.NET MVC 应用程序的 jquery ajax 发布(通过“数据”选项发布数据)。它一直有效,直到我决定添加集成 Windows 身份验证。我将 xhrFields: { withCredentials: true } 添加到 $.ajax 调用中以完成客户端身份验证。现在返回的数据为空。
这是我的服务器端启动:
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]字符串 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 始终为空。
最佳答案
好吧,我找到了答案,这很简单,但我仍然不知道幕后的细节,即为什么它起作用。只需将“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);
});
}
如果有人知道原因,请回复。谢谢!
关于jquery - Web API OWIN 从 $.AJAX POST withCredentials :true 接收空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43415458/