【问题标题】:System.ArgumentOutOfRangeException in c# Razor pages) when doing AJAX call from JavaScriptc# Razor 页面中的 System.ArgumentOutOfRangeException)从 JavaScript 进行 AJAX 调用时
【发布时间】: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。 d.MoveNext() --- 从先前抛出异常的位置结束堆栈跟踪 --- 在 Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.BindArgumentsCoreAsync() 在 Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync() 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker。 g__Awaited|24_0(ResourceInvoker 调用者,Task lastTask,State next,Scope 范围,对象状态,布尔 isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed 语境) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(状态&下一个,范围&范围,对象& 状态,布尔值& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- 从先前抛出异常的位置结束堆栈跟踪 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker。 g__Awaited|17_0(ResourceInvoker 调用者,Task 任务,IDisposable 范围) 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点端点, 任务 requestTask, ILogger logger) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

这个错误似乎是在服务器端接收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


【解决方案1】:

对不起,对我来说,不清楚您要做什么。 您的方法说 [FromBody],但是我在您的 ajax 请求中看不到正文。

Duration 是您希望在 ID 参数上接收的值吗?
url: "/Subjects/Choose?handler=Duration"。

如果是这样,那么您正在尝试将值作为查询字符串传递。 将您的方法更改为

([FromQuery]int id)

和你的 url 调用

url: "/Subjects/Choose?id=Duration"

或者另一种方法,改变你的路线到

@page "*here the current route*/{id}"

你的方法

([FromRoute]int id)

【讨论】:

  • 不行,我要发id,id是C#方法的参数 public IActionResult OnGetDuration([FromBody]int id)
  • 是的,但是您想如何发送它,作为正文或查询参数?您的 ajax 调用不发送任何 Id 并且不包含任何正文。 Net core 端无法将来自您的请求的任何数据与 id 参数绑定。
  • url: "/Subjects/Choose?handler=Duration"
  • 不一定,你的 url 可能没问题,但实际上它与方法签名不匹配。因为您的方法期望来自正文的 id,但您将其作为查询字符串传递。 “处理程序=持续时间”。将您的方法更改为 [FromQuery] 并将您的 url 调用更改为“/Subjects/Choose?id=Duration”
  • 感谢您的帮助。这个问题stackoverflow.com/questions/33341668/…帮助我解决了我的问题。
猜你喜欢
  • 2020-05-04
  • 1970-01-01
  • 2013-12-11
  • 2020-03-23
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多