javascript - HttpClient PostAsync 在 JQuery 中等效于 FormURLEncodedContent 而不是 JSON

标签 javascript c# jquery owin

我编写了一个 JQuery 脚本来执行用户登录 POST(尝试执行我在附加信息部分使用 C# 执行的操作,见下文)。

在我的 html 页面使用 JQuery 代码触发 POST 后,我发现了以下问题:

1 - 我调试了服务器端代码,我知道服务器收到了 POST(在 ValidateClientAuthentication() 函数,但不在 GrantResourceOwnerCredentials() 函数中)。
2 - 此外,在服务器端,我找不到任何用户名密码,应该用 postdata 发布。然而,对于用户端 C# 代码,当我调试到服务器端 C# 代码时,我可以在 context 变量中看到这些值。我认为,这就是问题的全部根源。
3 - JQuery 代码调用函数getFail()。

<强>? - 我想知道这个 JQuery 代码C# 用户端代码 有何不同strong> 下面,以及如何修复它,以便它们执行相同的工作?

(我的猜测:JSON.stringifyFormURLEncodedContent 做不同的东西)

JQuery/Javascript 代码:

function logIn() {
var postdata = JSON.stringify(
{
    "username": document.getElementById("username").value,
    "password": document.getElementById("password").value
});

try {
    jQuery.ajax({
        type: "POST",
        url: "http://localhost:8080/Token",
        cache: false,
        data: postdata,
        dataType: "json",
        success: getSuccess,
        error: getFail
    });
} catch (e) {
    alert('Error in logIn');
    alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
    alert('getSuccess in logIn');
    alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
    alert('getFail in logIn');
    alert(jqXHR.status); // prints 0
    alert(textStatus); // prints error
    alert(errorThrown); // prints empty
};

};

服务器端处理 POST (C#):

public override async Task ValidateClientAuthentication(
        OAuthValidateClientAuthenticationContext context)
    {
        // after this line, GrantResourceOwnerCredentials should be called, but it is not.
        await Task.FromResult(context.Validated());
    }


public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await manager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError(
                "invalid_grant", "The user name or password is incorrect.");
            context.Rejected();
            return;
        }

        // Add claims associated with this user to the ClaimsIdentity object:
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        foreach (var userClaim in user.Claims)
        {
            identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
        }

        context.Validated(identity);
    }

其他信息:在我的 C# Owin Web 服务器的 C# 客户端测试应用程序中,我有以下代码来执行 POST(工作正常):< br/> 用户端 POST (C#):

//...
HttpResponseMessage response;
var pairs = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>( "grant_type", "password"), 
    new KeyValuePair<string, string>( "username", userName ), 
    new KeyValuePair<string, string> ( "password", password )
};
var content = new FormUrlEncodedContent(pairs);

using (var client = new HttpClient())
{
    var tokenEndpoint = new Uri(new Uri(_hostUri), "Token"); //_hostUri = http://localhost:8080/Token
    response = await client.PostAsync(tokenEndpoint, content);
}
//...

最佳答案

不幸的是,dataType 控制着 jQuery 期望返回的 数据是什么,而不是 data 是什么。要设置请求 数据(data)的内容类型,您可以使用contentType: "json"。 (更多内容在 the documentation 中。)

var postdata = JSON.stringify( { "用户名": document.getElementById("用户名").value, “密码”:document.getElementById(“密码”).value });

jQuery.ajax({
    type: "POST",
    url: "http://localhost:8080/Token",
    cache: false,
    data: postdata,
    dataType: "json",
    contentType: "json",  // <=== Added
    success: getSuccess,
    error: getFail
});

如果您不想发送 JSON,而是想发送通常的 URI 编码表单数据,您根本不会使用 JSON.stringify并且直接将对象提供给 jQuery 的 ajax;然后 jQuery 将创建 URI 编码的表单。

try {
    jQuery.ajax({
        type: "POST",
        url: "http://localhost:8080/Token",
        cache: false,
        data: {
            "username": document.getElementById("username").value,
            "password": document.getElementById("password").value
        },
        dataType: "json",
        success: getSuccess,
        error: getFail
    });
    // ...

关于javascript - HttpClient PostAsync 在 JQuery 中等效于 FormURLEncodedContent 而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640624/

相关文章:

javascript - 邮政编码生成器 JQuery

javascript - 我如何以循环方式为图像制作动画?`

JQuery 删除错误的 li

javascript - 使用 mern.io 脚手架工具 - .need 方法是什么?

javascript - Knockout 无法解析绑定(bind)内部方法

javascript - mvc View 中的网格行选择

c# - 将对象注入(inject)表单

c# - WPF 自定义控件 : Bind CollectionViewSource to DependencyProperty

c# - Azure 生成资源组 C#

javascript - rails 最佳实践在哪里放置不显眼的 javascript