1

I have a razor page model. In this model there is a get-Method.

public IActionResult OnGetDuration([FromBody]int id)
    {
        Subject subject = _service.GetSubjectById(id);
        int duration = subject.LessonsPerWeek;
        return new JsonResult('a');
    }

I call this method with Ajax in JavaScript:

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')
    });
}

This leads to an error:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
  An unhandled exception has occurred while executing the request.

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken) at

Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterConte xt context, Encoding encoding) at

Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterConte xt context, Encoding encoding) at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext) at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value) at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageBinderFactory.<>c__DisplayClass3_0. <g__Bind|0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.BindArgumentsCoreAsync() at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

This error seems to be caused when receiving the json on server side.

An ID for example 81 is given to the ajax call. But I am receiving the parameter id = 0 on C#.

If I send the id as string the parameter received on C# is null.

This id leads to a Nullreference Excption in the GET C# method.

How can I solve this error ?

9
  • The console output (Error) is: Failed to load resource: the server responded with a status of 500 () Commented Nov 13, 2020 at 13:03
  • I cant find the request body in the developer tools of Microsoft Edge. Commented Nov 13, 2020 at 13:11
  • I cannot see a request body there but a request header. Commented Nov 13, 2020 at 13:23
  • This is the request header: Commented Nov 13, 2020 at 13:24
  • :authority: localhost:5001 :method: GET :path: /Subjects/Choose?handler=Duration&81&_=1605273709748 :scheme: https accept: application/json, text/javascript, /; q=0.01 accept-encoding: gzip, deflate, br accept-language: de,de-DE;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6 cache-control: 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 Commented Nov 13, 2020 at 13:25

1 Answer 1

0

Sorry, for me it is not clear what you are trying to do. Your method says [FromBody], however I can't see the body in your ajax request.

By chance is the Duration the value You want to receive on the ID parameter?
url: "/Subjects/Choose?handler=Duration".

If so, then You are trying to pass the value as query string. Change your method to

([FromQuery]int id)

and your url call to

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

Or another approache, change your route to

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

and your method to

([FromRoute]int id)
Sign up to request clarification or add additional context in comments.

6 Comments

No ,I want to send the id and the id is the parameter of the C# method public IActionResult OnGetDuration([FromBody]int id)
yes, but how do you want to send it, as body or query parameter? Your ajax call doesn't send any Id and doesn't include any body. Net core side is not able to bind any data coming from your request with the id parameter.
url: "/Subjects/Choose?handler=Duration"
No necessarily, you're url could be OK, but as it is, it doesnt match the method signature. Because your method is expecting the id from body, but you are passing it as query string. "handler=duration". Change your method to [FromQuery] and your url call to "/Subjects/Choose?id=Duration"
Thank you for your help. This issue stackoverflow.com/questions/33341668/… helped me to solve my problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.