Moritz Schmidt Moritz Schmidt -4 years ago 388
C# Question

SwashBuckle define Response Body on Error

My application is an ASP.NET Core 1.0 Web API.

I have the following Controller:

public async Task<IActionResult> GetSomeData(string someData)
return this.Ok(JsonConvert.SerializeObject("Data is: " + someData));

Whenever I pass for example the string "111", swagger is showing me the following message:

enter image description here

How can i achive a Response Body like:

"Please enter 5 numbers"

Thank you

Answer Source

You can annotate your actions with [ProducesResponseType(typeof(ModelStateDictionary), (int)HttpStatusCode.OK)] to return the typical Dictionary typed error messages like when using return BadRequest(ModelState).

But you can't return a text in the schema definition. It is there for json structures, not for error messages. Instead you should use xmldoc (and also enable it in swagger) to add descriptions to the parameters.

Update: Alternative of adding documentation of the parameters and their meaning

/// <summary>
/// Returns some data based on <paramref name="someData"/> parameter.
/// </summary>
/// <param name="someData">Some data. (Must be exactly 5 characters wide)</param>
/// <response code="200">Returns indexed tags on success</response>
/// <response code="400">Invalid data sent</response>
/// <returns>A paged list of results</returns>
[ProducesResponseType(typeof(MyReturnType), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetSomeData(string someData)

Also you need to enable building of xmldocs in your project's properties.

And add to your startup:

services.AddSwaggerGen(options =>
    var appEnv = PlatformServices.Default.Application;

    options.IncludeXmlComments(Path.Combine(appEnv.ApplicationBasePath, $"{appEnv.ApplicationName}.xml"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download