Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

c# - Swagger - how to remove XML as a formatting option; only want JSON formatting

I am building a WEB API project and it seems like I am unable to remove the default of Swagger defaulting to XML formatting. I tried removing the AddXmlSerializerFormatters method call but my controller responses fail at that point. Anyone have a simple way to eliminate all XML in Web API and Swagger and only support JSON? Below is my current code in Startup.cs

services.AddMvc(options =>
                {
                    options.InputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>();
                    options.OutputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter>();
                }).AddXmlSerializerFormatters();

            services.AddControllers().AddJsonOptions(options => {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                options.JsonSerializerOptions.DictionaryKeyPolicy = null;

            });

Controller code:

[HttpGet]
        [Route("/companies")]
        [ValidateModelState]
        [SwaggerOperation("GetCompanies")]
        public virtual IActionResult GetCompanies()
        {
            ICompanyRepository _companyRespository = new CompaniesRepository();
            List<Company> companies = _companyRespository.GetAll();
            return Ok(companies);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you got the [Produces("application/json")] attribute on your controller classes?

From Get started with Swashbuckle and ASP.NET Core:

Mark the model with attributes, found in the System.ComponentModel.DataAnnotations namespace, to help drive the Swagger UI components.

Add the [Produces("application/json")] attribute to the API controller. Its purpose is to declare that the controller's actions support a response content type of application/json.

The Response Content Type drop-down selects this content type as the default.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...