5

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 ?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1
  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( ... );
});

1 Comment

There is an extension method to do this. services.AddMvc().AddXmlSerializerFormatters() github.com/aspnet/Mvc/blob/1.0.0/src/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.