Posted on 23/04/2025 12:44:56
Hi
We have been looking into this.
This is due to a new feature for the /dwapi that has recently rolled out so that /dwapi can be used easier with tools like htmx.
What that feature does is that if you request "accept: text/html" together with "x-dw-template: MyModule/item.cshtml", the response object will be serialized to html using the passed template.
The problem is that if you "accept: text/html" but no x-dw-template, you get a bad request. We are now looking at to solve that so if x-dw-template is missing, it will serialize to json.
There is a workaround to disable the behavior by setting RespectBrowserAcceptHeader = False (which is default by MVC and Dynamicweb sets it to true)
using Dynamicweb.Host.Core;
using Microsoft.AspNetCore.Mvc;
public class PipelineExtensions : IPipeline
{
public int Rank => 200;
public void RegisterApplicationComponents(IApplicationBuilder app)
{
app.MapWhen(isMyApiPath, app =>
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
});
static bool isMyApiPath(HttpContext context) => context.Request.Path.StartsWithSegments("/myapi", StringComparison.OrdinalIgnoreCase);
}
public void RegisterServices(IServiceCollection services, IMvcCoreBuilder mvcBuilder)
{
services.Configure<MvcOptions>(options =>
{
options.RespectBrowserAcceptHeader = false;
});
}
public void RunInitializers()
{
}
}
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("myapi/test")]
public class MyApiController : ControllerBase
{
public class GreetingResponse
{
public string? Message { get; set; }
}
[HttpGet, Route("hi")]
public IActionResult Hi([FromQuery] string name = "World")
{
var response = new GreetingResponse
{
Message = $"Hello {name}!"
};
return Ok(response);
}
}