我在 asp.net core blazor 应用程序中遇到 ajax 请求的问题。我已经尝试了几乎所有我能在 stackoverflow 上找到的与 ajax post 调用结果相关的 400 错误请求 我有以下控制器
[Route("api/{controller}/{action}/{id?}")]
public class BoldReportsAPIController : ControllerBase, IReportController
{
// Report viewer requires a memory cache to store the information of consecutive client request and
// have the rendered report viewer information in server.
private IMemoryCache _cache;
// IHostingEnvironment used with sample to get the application data from wwwroot.
private IWebHostEnvironment _hostingEnvironment;
public BoldReportsAPIController(IMemoryCache memoryCache, IWebHostEnvironment hostingEnvironment)
{
_cache = memoryCache;
_hostingEnvironment = hostingEnvironment;
}
// Post action to process the report from server based json parameters and send the result back to the client.
[HttpPost]
public object PostReportAction([FromBody] Dictionary<string, object> jsonArray)
{
return ReportHelper.ProcessReport(jsonArray, this, this._cache);
}
}
但是当我进行 ajax 调用时,它会给出 400 bad request 错误。
我已经用邮递员生成的代码替换了原始的ajax调用,但该代码也不起作用。
var settings = {
"async": true,
"crossDomain": true,
"url": "https://localhost:44313/api/BoldReportsAPI/PostReportAction",
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "fbed680d-0143-ab86-24e6-176c16d713bf"
},
"processData": false,
"data": "{\"reportAction\":\"ReportLoad\",\"isReloadReport\":false,\"controlId\":\"report-viewer\",\"reportPath\":\"sales-order-detail\",\"enableVirtualEvaluation\":false,\"reportServerUrl\":\"\",\"processingMode\":\"remote\",\"locale\":\"en-US\",\"accessInternalValue\":false,\"customBrandSettings\":{\"hideHelpLink\":false,\"customDomain\":\"https://help.boldreports.com\",\"customBrandName\":\"Bold Reports\",\"customLinks\":[{\"name\":\"ESLicenseMessage\",\"url\":\"/licensing/license-token/\"}]}}\r\n"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
这是由于蚂蚁伪造令牌造成的。显然,ABP 会自动添加防伪令牌,因此添加后
[IgnoreAntiforgeryToken(Order = 2000)]
按照我的操作方法,问题已解决。
但感觉就像我破坏了安全性。
使用 ValidateAntiForgeryToken 时,您必须添加报告查看器 API 交互的标头。您可以参考以下文章来添加报表查看器交互的标题。这些需要使用 ReportViewer introp 添加。
在我的例子中,我将不带引号的数字作为字符串化的 json 对象值传递。我已经发现并修复了许多问题,直到我开始在 dotnet 8 中托管我的 api。现在看来序列化有点严格了。