Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ASP.NET web core API - incorrect default xml serialization in Swagger #39064

Closed
vsfeedback opened this issue Dec 15, 2021 · 3 comments
Closed
Labels
Author: Migration Bot 🤖 The issue was created by a issue mover bot. The author may not be the actual author. old-area-web-frameworks-do-not-use *DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels

Comments

@vsfeedback
Copy link

vsfeedback commented Dec 15, 2021

This issue has been moved from a ticket on Developer Community.


I'm using swagger/index page for testing my API. I need both JSON and XML serialization. Json is working fine but the xml serialization generated by swagger contains non-capital letters of node names for capital letter started properties of my [DataContract].

Steps:
1) Add XML serialization formatters:
builder. Services.AddControllers(). AddXmlSerializerFormatters();
2) Data contract class:
    [DataContract]
    public class DataRequest
    {
        [DataMember]
        public DateTime FromDate { get; set; }
        [DataMember]
        public DateTime ToDate { get; set; }
    }
3) Add EF controller with only one Post method:
  [HttpPost]
        public async Task<ActionResult<IEnumerable<DataReply>>> Request(DataRequest dataReply)
        {
            return await _context. DataReply.ToListAsync();
        }

Set break-point on return await at post-method.

4) Run (F5) and Try it out:
Json request (application/json):

{
  "fromDate": "2021-11-13T00:12:13.725Z",
  "toDate": "2021-11-13T00:12:13.725Z"
}

As result, request instance is correct (see attached picture "json serialization in swagger.png")

Xml request (application/xml):
<?xml version="1.0" encoding="UTF-8"?>
<DataRequest>
	<fromDate>2021-11-13T00:09:20.021Z</fromDate>
	<toDate>2021-11-13T00:09:20.022Z</toDate>
</DataRequest>

As result, request instance is incorrect - all dates are 01.01.0001 ... (see attached picture "xml serialization in swagger.png")

Obviously, the problem is a incorrect node names - fromDate and toDate. The correct names must be FromDate and ToDate accordingly. The workout is rename these tags manually but much more better to fix the swagger behaviour for XML serialization.

Thanks a lot.


Original Comments

Feedback Bot on 11/14/2021, 11:25 PM:

We have directed your feedback to the appropriate engineering team for further evaluation. The team will review the feedback and notify you about the next steps.

Feedback Bot on 12/15/2021, 11:52 AM:

This issue is currently being investigated. Our team will get back to you if either more information is needed, a workaround is available, or the issue is resolved.

@ghost ghost added the Author: Migration Bot 🤖 The issue was created by a issue mover bot. The author may not be the actual author. label Dec 15, 2021
@rafikiassumani-msft rafikiassumani-msft added the old-area-web-frameworks-do-not-use *DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels label Dec 15, 2021
@rafikiassumani-msft
Copy link
Contributor

rafikiassumani-msft commented Dec 15, 2021

I tried to reproduce the issue. Below is an API setup that does not properly render an xml response document in the swagger-ui. There are two problems:

  1. The Swagger-ui does not generate proper xml response for return of array types
  2. Improper binding due to CamelCasing of dates fields
         // POST api/<ValuesController>
        [HttpPost]
        [Produces("application/xml")]
        [Consumes("application/xml")]  
        public async Task<ActionResult<IEnumerable<DataReply>>> Post([FromBody] DataRequest dataRequest)
 
        {
 
            _dbContext.DataReplies.Add(new DataReply
 
            {
                FromDate = dataRequest.FromDate,
                ToDate = dataRequest.ToDate,
 
            });

            await _dbContext.SaveChangesAsync();
            return await _dbContext.DataReplies.ToListAsync();
        }
 
// Models

    [DataContract]
    public class DataReply
    {
        public int DataReplyId { get; set; }

        [DataMember]
        public DateTime? FromDate { get; set; }

        [DataMember]
        public DateTime? ToDate { get; set; }
    }

    [DataContract]
    public class DataRequest
    {
        [DataMember]
        [Required]
        public DateTime? FromDate { get; set; }

        [DataMember]
        [Required]
        public DateTime? ToDate { get; set; }
    }

This results in the following issue in swagger-ui :

image

I tried to track down the swagger-ui issue and it appears that it's an existing issue with the dependency that Swashbuckle is using for the UI. See the following issue: swagger-api/swagger-ui#4650 ·
The problem happens when the user is expecting an array of objects to be serialized to xml. This is something we might need to figure out a fix by allowing the user to set the main node attribute for lists or Arrays return types.

For the second issue of CamelCasing in the request that results in improper binding, from my preliminary research, this might be a bug. When you add the `[Required] attribute, there are validation failures.

image

After removing the [Required] attribute, the following binding issue happens:

image

@rafikiassumani-msft rafikiassumani-msft added this to the .NET 7 Planning milestone Dec 21, 2021
@ghost
Copy link

ghost commented Dec 21, 2021

Thanks for contacting us.

We're moving this issue to the .NET 7 Planning milestone for future evaluation / consideration. We would like to keep this around to collect more feedback, which can help us with prioritizing this work. We will re-evaluate this issue, during our next planning meeting(s).
If we later determine, that the issue has no community involvement, or it's very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues.
To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

@rafikiassumani-msft
Copy link
Contributor

After some further investigations we found that the binding failures are due to the fact that XML is case sensitive. In the case above Shashbuckle is using the JSON camelCase serialization. You can change the behavior globally by adding the following configuration:

builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(opts =>
{
    opts.JsonSerializerOptions.PropertyNamingPolicy = null;

});

I will close this issue since there is no further action on our side.

@ghost ghost locked as resolved and limited conversation to collaborators Jan 26, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Author: Migration Bot 🤖 The issue was created by a issue mover bot. The author may not be the actual author. old-area-web-frameworks-do-not-use *DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels
Projects
None yet
Development

No branches or pull requests

2 participants