Skip to main content
 首页 » 编程设计

c#之AJAX 发布数据到达 ASP.NET Core 2.1 Controller 时为空

2024年02月25日35mfrbuaa

我正在使用以下 jQuery 代码将数据发布到 ASP.NET Core MVC 2.1.2 页面:

function OnCountryChange() { 
    $.ajax({ 
        url: "/OnCountryChange", 
        type: "POST", 
        contentType: "application/json; charset=utf-8", 
        datatype: "json", 
        headers: { 
            "RequestVerificationToken": $('input[name = __RequestVerificationToken]').val() 
        }, 
        data: JSON.stringify({ 
            sCountryCode: "Test 123" 
        }) 
    }); 
} 

我正在使用这种方法在 Controller 中接收帖子:

[HttpPost] 
[ValidateAntiForgeryToken] 
[Route("/OnCountryChange")] 
public IActionResult OnCountryChange([FromBody] string sCountryCode) 
{ 
    logger.LogDebug($"Country code is: {sCountryCode ?? "null"}"); 
 
    return Json(sCountryCode); 
} 

打印到日志的输出是:

Country code is: null

原始请求正文(使用 Fiddler 查看)如下所示:

{"sCountryCode":"Test 123"} 

为什么没有传递数据?

请您参考如下方法:

我不熟悉C#,但是在你的问题中你添加了

contentType: "application/json; charset=utf-8" 

在你的Ajax方法中,这意味着数据参数是json格式,所以你需要访问json对象而不是直接访问字符串.

两种解决方法:

一个。更改您的 C# Controller 方法以像访问 json 对象一样访问

发送不带json的Ajax参数,类似下面的代码:

function OnCountryChange() { 
    $.ajax({ 
        url: "/OnCountryChange", 
        type: "POST", 
        datatype: "json", 
        headers: { 
            "RequestVerificationToken": $('input[name = __RequestVerificationToken]').val() 
        }, 
        data: {sCountryCode: "Test 123"} 
    }); 
}