lonix
lonix

Reputation: 21011

Return empty response from ASP.NET Core for HTMX

I'm trying to add HTMX to a project that uses Razor Pages and MVC controllers.

I have a form submitted by HTMX. It's handled by an MVC action, which returns a status code and empty response.

[Controller]
public class CustomerController : Controller
{

  [HttpPost]
  public async Task<IActionResult> CreateCustomer(CustomerDto dto)
  {
    // errors: return other status codes...

    // success: return 204 for HTMX (not 200)
    return NoContent();
  }

}

The correct status code is returned, so the HTMX event handlers take appropriate action.

However the response always includes a body; specifically, 400...599 error pages. This particular action does not render a view, so I don't understand why it's happening.

What is the problem, and how do I fix it?

(ASP.NET Core v8)

Upvotes: 1

Views: 76

Answers (1)

lonix
lonix

Reputation: 21011

That the response contains an error page was the hint I needed to resolve the issue.

I realised the configuration included the Status Code Pages middleware, with the UseStatusCodePagesWithReExecute option. So when returning a status code in the 400...599 range, the middleware would automatically re-execute the request and show a standard error page. One doesn't inspect the configuration often, so this was easy to forget / overlook.

I haven't read that docs page in years, but upon rereading it discovered that there's a nice feature to skip the middleware. The easiest is with an attribute on a Razor Pages page handler or MVC action. So in this case:

[SkipStatusCodePages]
[HttpPost]
public async Task<IActionResult> CreateCustomer(CustomerDto dto) { }

Now it returns the status code and an empty response, and HTMX can handle the rest.

Upvotes: 1

Related Questions