I would like to configure one (and only one) of my Controller to accept only application/xml
requests.
In the past i used IControllerConfiguration to do that like described here (Per-Controller configuration).
How can i do that in Aspnet Core ?
You can use the Consumes
-Annotation together with the accepted content type on Controller or Action level.
With
[Consumes("application/xml")]
public class MyController : Controller
{
public IActionResult MyAction([FromBody] CallModel model)
{
....
}
}
calls to this controller will only succeed if the client provides Content-Type header of application/xml
. Otherwise a 415 (Unsupported Media Type) will be returned.
You may simply check Request AcceptTypes / Content-Type headers (like if request.AcceptTypes.Contains("application/xml")
) and stop request processing.
Accordingly to link you provided, seems like you just want to ignore content type and always return an XML result. In this case you may use a new Produces attribute.
A filter that specifies the expected System.Type the action will return and the supported response content types. The Microsoft.AspNetCore.Mvc.ProducesAttribute.ContentTypes value is used to set Microsoft.AspNetCore.Mvc.ObjectResult.ContentTypes.
Apply attribute to your controller
[Produces("application/xml")]
public YourXmlController : Controller { }
or only to specific controller action:
[Produces("application/xml")]
public Object ControllerAction()
{
return new { text = "hello world" };
}
Note, that XML formatter does not enabled by default, so you should add one using MvcOptions:
services.Configure<MvcOptions>(options =>
{
//options.InputFormatters.Add( ... );
//options.OutputFormatters.Add( ... );
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With