Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller Configuration in AspNetCore

Tags:

asp.net-core

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 ?

like image 317
dknaack Avatar asked Aug 02 '16 08:08

dknaack


2 Answers

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.

like image 50
Ralf Bönning Avatar answered Oct 23 '22 14:10

Ralf Bönning


  1. You may simply check Request AcceptTypes / Content-Type headers (like if request.AcceptTypes.Contains("application/xml")) and stop request processing.

  2. 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( ... );
});
like image 1
Set Avatar answered Oct 23 '22 13:10

Set