Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created April 19, 2011 17:50
Show Gist options
  • Save beccasaurus/929007 to your computer and use it in GitHub Desktop.
Save beccasaurus/929007 to your computer and use it in GitHub Desktop.
Without this, returning a 400 gives you just "Bad Request" ... with this, you can return a custom response

If you don't have the XML snippet below in your Web.config and your .NET app tries to return a 400 with custom data, you get this:

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 19 Apr 2011 17:47:46 GMT
Content-Length: 11

Bad Request

NOTE You only get this if you're making requests from a REMOTE IP! If you're testing from localhost, you won't see this. You'll see the custom response you want. Don't be fooled! Test your service from a remote machine!

Ok, so ... with this stuff in your Web.config, you'll get what you want:

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 19 Apr 2011 17:49:02 GMT
Content-Length: 25

{"my":["custom", "json"]}
<?xml version="1.0"?>
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
</configuration>
@iqueryable
Copy link

Thanks 👍

@astamatov
Copy link

This works great for returning json, but this will cause problem with 404 redirection - it would not work. Do you have a clue how to have both working?

@in8Sukka
Copy link

in8Sukka commented Feb 9, 2021

What if i am getting this error in an Azure function?

@markashleybell
Copy link

Thank you! This was super useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment