Hi @Nithin ,
Web API 415: Unsupported Media Type
In Asp.Net Core API application, if not add the binding source attributes like [FromBody]
or [FromForm]
(refer to the above code), on the Post method when bind the complex object, it will find the action parameter value from the request body(the Content-Type: application/json
), if you transfer the parameter value from the request Form (application/x-www-form-urlencoded
), it will show the 415 error.
How can I support two content types for an endpoint
- application/x-www-form-urlencoded
- application/json
To let one endpoint to support two content types, you can try to use custom model binding. In the custom model binder method, you can check the request content type, then based on the content type to get the parameter value from the request Form or request body, then create the object instance and return to the API method.
For example, create an asp.net 6 API application:
- Create a Student class:
- Add the API controller as below:
- Add the custom model binder: [Note] need to install the Newtonsoft.Json package.
- Register the custom model binder in the program.cs file. [Note] We need to allow Synchronous IO to get the value from the request body.
You can view the source code, it contains all above code: 219796-sourcecode.txt
Then the result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion