我正在开发一个带有多个端点的简单.NET Core API。
我需要将请求中的Content-Type作为特定于供应商的媒体类型返回,“application / vnd.com.myhomepay.api.ste.location-code + json”。但是,每当我设置Response.Headers.Add(“Content-Type”,“application / vnd.com.myhomepay.api.ste.location-code + json”)时,我都会得到一个带有Response的406状态代码。我已经阅读了我需要将此自定义MediaTypeHeaderValue添加到SupportedMediaTypes列表的位置,但我无法弄清楚如何在.Net Core中执行此操作。任何有关实现此目的的提示或建议。我还阅读了使用IOutputFormatter的更复杂的方法。
每个端点都有自己的供应商特定符号,将在Response的Content-Type标头中传回。
我尝试过的选项1:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true;
options.FormatterMappings.SetMediaTypeMappingForFormat("application/json", "application/vnd.com.myhomepay.api.ste.location-code+json;version=1");
options.FormatterMappings.SetMediaTypeMappingForFormat("application/json", "application/vnd.com.myhomepay.api.ste.tax-calculation+json;version=1");
});
}
Controller.cs
[Produces("application/vnd.com.myhomepay.api.ste.location-code+json;version=1")]
[HttpGet]
public IActionResult Get()
{
DailyReportAbbreviated dailyreport;
.....
return new OkObjectResult(dailyreport);
}
请求“Accept”标头设置为“application / vnd.com.myhomepay.api.ste.location-code + json; version = 1”
这将返回Status Cod 406 Not Acceptable
选项2:
我刚从控制器中删除了“Produces”属性并添加了:
Controller.cs
[HttpGet]
public IActionResult Get()
{
DailyReportAbbreviated dailyreport;
.....
Response.Headers.Add("Content-Type", "application/vnd.com.myhomepay.api.ste.location-code+json");
return new OkObjectResult(dailyreport);
}
这将返回Status Cod 406 Not Acceptable
选项3:
此选项似乎正在运作
Starup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true;
options.OutputFormatters.Insert(0, new JsonOutputFormatter());
});
}
JsonOutputFormatter.cs
public class JsonOutputFormatter : IOutputFormatter
{
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
return true;
}
public async Task WriteAsync(OutputFormatterWriteContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var response = context.HttpContext.Response;
//context.ContentType returns the string set on the "Produces" attribute that is set on the controller
response.ContentType = context.ContentType.ToString();
using (var writer = context.WriterFactory(response.Body, Encoding.UTF8))
{
await writer.WriteAsync(JsonConvert.SerializeObject(context.Object));
}
}
}
Controller.cs
[Produces("application/vnd.com.myhomepay.api.ste.location-code+json;version=1")]
[HttpGet]
public IActionResult Get()
{
DailyReportAbbreviated dailyreport;
.....
return new OkObjectResult(dailyreport);
}