fix(blogs): accept JSON on POST /api/v1/blog (no file)

BlogApiController.PostBlog called Request.Form.Files
unconditionally, which throws on a plain JSON body — the
exception is "This request does not have a Content-Type header.
Forms are available from requests with bodies like POSTs and a
form Content-Type of either application/x-www-form-urlencoded or
multipart/form-data."

That broke PostIt's first-bill-of-blog flow: the client posts a
BlogPost as JSON and has no files to attach. The endpoint
contract is [FromBody] BlogPost, so the JSON body is deserialised
into 'blog' as expected — only the IFormFileCollection argument
to BlogSpotService.Create needs a real-or-empty value.

Branch on Request.HasFormContentType: pass the form files when
present, pass an empty FormFileCollection otherwise. BlogSpotService
already short-circuits on a null/empty file collection, so the
JSON-only path is now a clean code path.

Tests: add PostBlog_creates_a_post_and_Get_returns_it_in_the_list
(POST a draft, assert 201 + server-assigned Id, GET the index,
assert exactly one entry with that Id). Add a per-test
ResetDatabase helper because the in-memory store is shared across
the lifetime of the BlogsWebServerFixture instance.
This commit is contained in:
Paul Schneider 2026-07-06 22:03:41 +01:00
commit 6d222cf819
2 changed files with 81 additions and 1 deletions

View file

@ -92,7 +92,29 @@ namespace Yavsc.Blogs.Controllers
return BadRequest(ModelState);
}
var post = blogSpotService.Create(User.GetUserId(), blog, Request.Form.Files);
// The BlogSpotService.Create() signature requires an
// IFormFileCollection for file uploads. Reading
// Request.Form.Files when the request is a plain JSON
// body (e.g. from PostIt) throws
// "This request does not have a Content-Type header.
// Forms are available from requests with bodies like
// POSTs and a form Content-Type of either
// application/x-www-form-urlencoded or
// multipart/form-data."
//
// Two valid use cases for this endpoint:
// 1. JSON body only (no files) — PostIt path.
// 2. multipart/form-data with a 'blog' field + 0..N
// files — future browser / server-rendered path.
//
// Branch on HasFormContentType: pass the form files when
// present, pass an empty collection otherwise. The
// FileSystem branch in BlogSpotService.Create then
// short-circuits to "no files to handle".
var files = Request.HasFormContentType
? Request.Form.Files
: (IFormFileCollection)new FormFileCollection();
var post = blogSpotService.Create(User.GetUserId(), blog, files);
return CreatedAtRoute("GetBlog", new { id = post.Id }, post);
}