【发布时间】:2021-02-25 11:36:47
【问题描述】:
我有一个剃须刀页面模型。在这个模型中有一个 get-Method。
public IActionResult OnGetDuration([FromBody]int id)
{
Subject subject = _service.GetSubjectById(id);
int duration = subject.LessonsPerWeek;
return new JsonResult('a');
}
我在 JavaScript 中用 Ajax 调用这个方法:
function getHours(i, studentId) {
var selection = document.getElementById('select_' + i);
var id = parseInt(selection.options[selection.selectedIndex].value);
var json = JSON.stringify(id);
$.ajax({
type: 'GET',
contentType: 'application/json',
data: json,
dataType: 'json',
url: "/Subjects/Choose?handler=Duration",
cache: false,
success: function (result) {
alert(result);
},
error: alert('error calling my ajax request')
});
}
这会导致错误:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.ArgumentOutOfRangeException:指定的参数超出了有效值的范围。 在 System.Text.Json.JsonSerializer.ReadAsync[TValue](流 utf8Json,类型 returnType, JsonSerializerOptions 选项,CancellationToken cancelToken) 在
Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterConte xt 上下文,编码编码) 在
Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterConte
xt 上下文,编码编码)
在 Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext
绑定上下文)
在 Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext,
IModelBinder modelBinder、IValueProvider valueProvider、ParameterDescriptor 参数、ModelMetadata
元数据,对象值)
在 Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageBinderFactory.c__DisplayClass3_0。
这个错误似乎是在服务器端接收json时引起的。
为 ajax 调用提供了一个 ID,例如 81。但我在 C# 上收到参数 id = 0。
如果我将 id 作为字符串发送,则在 C# 上收到的参数为 null。
此 id 导致 GET C# 方法中的 Nullreference Excption。
我该如何解决这个错误?
【问题讨论】:
-
控制台输出(错误)为:加载资源失败:服务器响应状态为500()
-
我在 Microsoft Edge 的开发者工具中找不到请求正文。
-
我在那里看不到请求正文,但看到了请求标头。
-
这是请求头:
-
:authority: localhost:5001 :method: GET :path: /Subjects/Choose?handler=Duration&81&_=1605273709748 :scheme: https 接受: application/json, text/javascript, /; q=0.01 接受编码:gzip, deflate, br 接受语言:de,de-DE;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6 缓存控制: no-cache content-type: application/json pragma: no-cache referer: localhost:5001/Subjects/Choose?id=10 sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: same-origin
标签: javascript c# asp.net ajax razor-pages