我想让控制器动作返回css。
只有当响应类型为text/css时,浏览器才会使用CSS。
这是我的行动。
[HttpGet("{tenant}/stylesheet")]
[Produces("text/css")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<ActionResult<BrandingDTO>> Stylesheet(string tenant)
{
Branding b = dbContext.Branding.SingleOrDefault(z => z.Tenant == tenant);
if (t == null)
{
return NotFound(); // Actually returns 406 unacceptable.
}
return Ok(Content($@"
nav.navbar {{
background-color: {b.PrimaryBrandingColour};
}}
", "text/css"));
}在“找不到”的情况下,我不需要响应为application/problem+json,但事实恰好是这样的。
我不得不创建一个自定义输出格式化程序。
/// <summary>
/// https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/custom-formatters?view=aspnetcore-6.0
/// </summary>
internal class CssOutputFormatter : TextOutputFormatter
{
public CssOutputFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/css"));
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
protected override bool CanWriteType(Type? type)
{
return type == typeof(ContentResult) || type == typeof(string);
}
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
string buffer = context.Object.ToString();
ContentResult content = context.Object as ContentResult;
if(content != null)
{
buffer = content.Content;
}
await context.HttpContext.Response.WriteAsync(buffer, selectedEncoding);
}
}问题是,在未找到的情况下,这个响应实际上是406不可接受的;我期望404和text/css类型的空体或application/problem+json类型的非空体。
这个能行吗?或者,我是否应该接受的回应要么是202个与text/css的其他中断?
发布于 2022-09-21 10:53:07
希望这能帮到你。
HttpResponseMessage message=new HttpResponseMessage(HttpStatusCode.OK);
string color = "black";
string content = $"nav.navbar {{background-color: {color};}}";
message.Content=new StringContent(content, System.Text.Encoding.UTF8, "text/plain");
return Ok(message);https://stackoverflow.com/questions/73799187
复制相似问题