Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

InvalidOperationException: Incorrect Content-Type: application/json #2749

Closed
FabienDehopre opened this issue Jun 26, 2015 · 6 comments
Closed
Assignees
Milestone

Comments

@FabienDehopre
Copy link

When I POST to a controller using a json payload, I receive an InvalidOperationException: Incorrect Content-Type: application/json

Here is the raw request (captured by fiddler):

POST http://localhost:32064/api/registration HTTP/1.1
Host: localhost:32064
Connection: keep-alive
Content-Length: 293
Accept: application/json
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Content-Type: application/json
CSP: active
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
Postman-Token: f909aeb3-476d-aee6-1e7a-a48a77ae2e08
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fr;q=0.6,fr-FR;q=0.4,nl;q=0.2

{
    "lastName": "test",
    "firstName": "test",
    "email": "[email protected]",
    "function": "test",
    "company": "test",
    "phone": "0123456789",
    "club": null,
    "federationNumber": null,
    "handicap": null,
    "registerForTournament": false,
    "comment": "test"
}

the headers of the response:

HTTP/1.1 500 Internal Server Error
Transfer-Encoding: chunked
Content-Type: text/html
Server: Microsoft-IIS/10.0
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcRmFiaWVuXERldnNcSWN0N1Nwb25zb3Jpbmcgdk5leHRcSWN0N1Nwb25zb3Jpbmdcd3d3cm9vdFxhcGlccmVnaXN0cmF0aW9u?=
X-Powered-By: ASP.NET
Date: Fri, 26 Jun 2015 08:48:33 GMT

and finally the stacktrace:

InvalidOperationException: Incorrect Content-Type: application/json
Microsoft.AspNet.Http.Core.FormFeature.<ReadFormAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.AntiForgeryTokenStore.<GetFormTokenAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.AntiForgeryWorker.<ValidateAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.AntiForgery.<ValidateAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.ValidateAntiForgeryTokenAuthorizationFilter.<OnAuthorizationAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.Core.FilterActionInvoker.<InvokeAuthorizationFilterAsync>d__35.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.Core.FilterActionInvoker.<InvokeAllAuthorizationFiltersAsync>d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.Core.FilterActionInvoker.<InvokeAsync>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.MvcRouteHandler.<InvokeActionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.MvcRouteHandler.<RouteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Routing.Template.TemplateRoute.<RouteAsync>d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.Routing.InnerAttributeRoute.<RouteAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Routing.RouteCollection.<RouteAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Cors.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.ErrorPageMiddleware.<Invoke>d__4.MoveNext()
@davidfowl
Copy link
Member

Can you show your controller?

@FabienDehopre
Copy link
Author

I just realize that I put a ValidateAntiForgeryToken attribute on my method.
When I remove it, it works correctly.
Anyway, here is my controller (before I remove the attribute):

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Ict7Sponsoring.DTOs;
using Ict7Sponsoring.Filters;
using Ict7Sponsoring.Models;
using Microsoft.AspNet.Mvc;

namespace Ict7Sponsoring.Controllers
{
    [Route("api/[controller]")]
    public class RegistrationController : Controller
    {
        private readonly SubscriptionContext _context;
        private readonly SendGridMail _sendGridMail;

        public RegistrationController(SubscriptionContext context, SendGridMail sendGridMail)
        {
            _context = context;
            _sendGridMail = sendGridMail;
        }

        [HttpPost("")]
        [ValidateAntiForgeryToken]
        [ValidateModelState]
        public async Task<IActionResult> Register(SubscriptionDTO dto)
        {
            try
            {
                using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    if (_context.Subscriptions.Any(x => x.Email == dto.Email))
                    {
                        ModelState.AddModelError("Email", "E-mail address already registered !!!");
                        return HttpBadRequest(ModelState);
                    }

                    var subscription = new Subscription
                    {
                        LastName = dto.LastName,
                        FirstName = dto.FirstName,
                        Email = dto.Email,
                        Function = dto.Function,
                        Company = dto.Company,
                        Phone = dto.Phone,
                        Club = dto.Club,
                        FederationNumber = dto.FederationNumber.GetValueOrDefault(),
                        Handicap = dto.Handicap.GetValueOrDefault(),
                        RegisterForTournament = dto.RegisterForTournament,
                        Comment = dto.Comment
                    };
                    _context.Subscriptions.Add(subscription);
                    await _context.SaveChangesAsync();
                    await _sendGridMail.SendMail(subscription);
                    tran.Complete();
                    return new HttpStatusCodeResult(200);
                }
            }
            catch (Exception ex)
            {
                return HttpBadRequest(ex);
            }
        }
    }
}

and just in case, the validatemodelstate class:

using Microsoft.AspNet.Mvc;

namespace Ict7Sponsoring.Filters
{
    public class ValidateModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new BadRequestObjectResult(context.ModelState);
            }
        }
    }
}

@davidfowl
Copy link
Member

We should be checking the content type before reading the form. I still don't like how aggressively ReadForm fails when the content type is wrong but meh.

/cc @rynowak @Tratcher

@danroth27 danroth27 added this to the 6.0.0-beta7 milestone Jun 26, 2015
@rynowak
Copy link
Member

rynowak commented Jun 26, 2015

@davidfowl - agreed, we should make this fail more gracefully.

@danroth27 danroth27 modified the milestones: 6.0.0-beta6, 6.0.0-beta7 Jul 7, 2015
@danroth27 danroth27 modified the milestones: 6.0.0-beta7, 6.0.0-beta6 Jul 16, 2015
@rynowak
Copy link
Member

rynowak commented Aug 7, 2015

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants