Home > Software design >  How to return 404 on malformed URL segment in ASP.NET Core API
How to return 404 on malformed URL segment in ASP.NET Core API

Time:07-29

Consider this ASP.NET 6.0 API Controller:

[ApiController]
public class FooController
{
    [HttpGet("foo/{guid}")]
    public Guid Get(Guid guid) => guid;
}

Not surprisingly, you can request it with a GUID like this:

GET /foo/a2efa3af-8c53-4cba-aa1c-caa3be1afb5b HTTP/1.1

HTTP/1.1 200 OK
"a2efa3af-8c53-4cba-aa1c-caa3be1afb5b"

If, on the other hand, you request an address where the URL segment corresponding to the guid parameter is malformed, you get a 400 Bad Request:

GET /foo/bar HTTP/1.1

HTTP/1.1 400 Bad Request
Content-Type: application/problem json; charset=utf-8
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-51853ab7480e55c91ebffe5934d29d0c-a2150bd8796a0d41-00",
  "errors": { "guid": [ "The value 'bar' is not valid." ] }
}

While I understand why that happens, I'd like to change the behaviour. The fact that bar isn't a GUID is an implementation detail that I wouldn't like to surface.

Rather, I'd consider it appropriate for the response to be 404 Not Found, since the address /foo/bar clearly doesn't exist.

How can I change this behaviour?

Obviously, I can change the guid parameter type to a string and do imperative parsing, but is there a way I can keep the parameter a Guid and also return 404 Not Found on input that doesn't parse to a Guid?

CodePudding user response:

if you don't want to make manual valudation you can use Routing Constrains With Attribute Routing

 [HttpGet("foo/{guid:Guid}")]
 public Guid Get(Guid guid) => guid;
  • Related