Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException: Incorrect Content-Type: Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()

I am new to Asp.net MVC Core. I am working on Server-side loading of JQuery Datatables.net using Asp.Net Core MVC Middleware.

I have used this tutorial to learn how to create a handler and then this article to migrate to middleware but are running into some issues that I hope you can help me with.

I have refined using this tutorial

I get error

"InvalidOperationException: Incorrect Content-Type: Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()"

when I run the solution.

Here is my code: View

<script type="text/javascript">
    $(document).ready(function () {
        $('#datatable').DataTable({
            //"paging": true,
            //"ordering": true,
            //"info": true,
            'columns' : [
                { 'data': 'InsertedDateUtc' },
                //{ 'data': 'EventId' },
                { 'data': 'UserId' },
                { 'data': 'Action' },
                { 'data': 'Context' },
                { 'data': 'RecordId' },
                { 'data': 'Property' },
                { 'data': 'OldValue' },
                { 'data': 'NewValue' },
            ],
            'processing': true,
            'serverSide': true,

            'ajax' : {
                'type' : 'POST',
                'url' : '../AuditEventData.cs',
                //'url': '../APIController/GetAuditEvents'
                //'url' : '@Url.Action("GetAuditEvents", "APIController")'
                'datatype': 'json',
            }
        });
    });
</script>

Middleware

public class AuditEventData 
{
    private readonly RequestDelegate _next;
    private readonly IDataGet _dataGet;

    public AuditEventData(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        string result = null;
        int filteredCount = 0;

        var draw = httpContext.Request.Form["draw"].FirstOrDefault();
        var start = int.Parse(httpContext.Request.Form["start"].FirstOrDefault());
        var length = int.Parse(httpContext.Request.Form["length"].FirstOrDefault());
        var sortCol = int.Parse(httpContext.Request.Form["columns[" + httpContext.Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault());
        var sortDir = httpContext.Request.Form["order[0][dir]"].FirstOrDefault();
        var search = httpContext.Request.Form["search[value]"].FirstOrDefault();

        try
        {
            var auditEvents = await _dataGet.GetServerSideAuditEvents(length, start, sortCol, sortDir, search);

            filteredCount = auditEvents.Count();

            var data = new
            {
                iTotalRecords = await _dataGet.GetTotalAuditEventCount(),
                iTotalDisplayRecords = filteredCount,
                aaData = auditEvents
            };

            result = JsonConvert.SerializeObject(data);
            await httpContext.Response.WriteAsync(result);

        }
        catch (Exception e)
        {
            await ErrorHandler.HandleException(e);
        }

            await _next(httpContext);
    }

}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseAuditEventDataMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AuditEventData>();
    }
}

Startup.cs

app.MapWhen(
            context => context.Request.Path.ToString().EndsWith("ViewAudit"),
            appBranch =>
            {
                appBranch.UseAuditEventDataMiddleware();
            });

In the middleware class the line

var start = int.Parse(httpContext.Request.Form["start"].FirstOrDefault());

gives me the error - the tutorials and Microsoft documentation here seem to indicate that I do not need to use the ".Form" and should be able to just use

var start = int.Parse(httpContext.Request["start"].FirstOrDefault());

however, when I do that, I get this error

cannot apply indexing with [] to an expression of type 'HttpRequest'

I cannot find any examples on how to do this and any help will be appreciated

Thanks

like image 709
Ferdi Avatar asked Aug 23 '26 19:08

Ferdi


1 Answers

In order to expect to have a Form in your HttpContext.Request you must change your ajax datatype to 'application/x-www-form-urlencoded'. Now whether you want to do that is another question.

From here: https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data

like image 177
Serj Sagan Avatar answered Aug 26 '26 14:08

Serj Sagan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!