Gqq*_*big 4 c# asp.net-core asp.net-core-2.0
我在 Startup 类中设置了缩进 JSON,但是如何从控制器中检索格式值?
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddWebApiConventions()
.AddJsonOptions(options=> options.SerializerSettings.Formatting=Newtonsoft.Json.Formatting.Indented);
}
}
public class HomeController : Controller
{
public bool GetIsIndented()
{
bool isIndented = ????
return isIndented;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将 的实例注入IOptions<MvcJsonOptions>到您的控制器中,如下所示:
private readonly MvcJsonOptions _jsonOptions;
public HomeController(IOptions<MvcJsonOptions> jsonOptions, /* ... */)
{
_jsonOptions = jsonOptions.Value;
}
// ...
public bool GetIsIdented() =>
_jsonOptions.SerializerSettings.Formatting == Formatting.Indented;
Run Code Online (Sandbox Code Playgroud)
有关(选项模式)的更多信息,请参阅文档IOptions。
如果您只关心 ,则Formatting可以稍微简化一下,只需使用一个bool字段,如下所示:
private readonly bool _isIndented;
public HomeController(IOptions<MvcJsonOptions> jsonOptions, /* ... */)
{
_isIndented = jsonOptions.Value.SerializerSettings.Formatting == Formatting.Indented;
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,不需要这个GetIsIndented函数。
| 归档时间: |
|
| 查看次数: |
669 次 |
| 最近记录: |