Using c# web api with alternate content-type

2019-04-23 21:08发布

I'm new to web api and I need to create a server for a client. I have no control over the client - can't change a thing.

The client sends in an html encapsulated json request in a POST body. However, the content-type can vary. What do I need to do to allow my ApiController to process different content-types?

1条回答
孤傲高冷的网名
2楼-- · 2019-04-23 21:45

Under the hood, Web Api supports Content Negotiation mechanism to automatically opt the correct formatter based on the header Content-Type in HTTP request.

By default content negotiation supports three formatters: json, xml and form-urlencoded data. If no formatter found, client will receives HTTP error 406 (Not Acceptable).

See more:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/content-negotiation

If you need to allow Web Api support another Content-Type, you can write your own custom formatter:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/media-formatters

查看更多
登录 后发表回答