c# - How to customize error message for 415 status code? -


we have restricted media type 'application/json'. if request header contains 'content-type: text/plain', responds below error message , status code 415. behavior expected send empty response status code 415. how can in .net web api?

{    "message": "the request entity's media type 'text/plain' not supported resource.",    "exceptionmessage": "no mediatypeformatter available read object of type 'mymodel' content media type 'text/plain'.",    "exceptiontype": "system.net.http.unsupportedmediatypeexception",    "stacktrace": "   @ system.net.http.httpcontentextensions.readasasync[t](httpcontent content, type type, ienumerable`1 formatters, iformatterlogger formatterlogger, cancellationtoken cancellationtoken)\r\n   @ system.web.http.modelbinding.formatterparameterbinding.readcontentasync(httprequestmessage request, type type, ienumerable`1 formatters, iformatterlogger formatterlogger, cancellationtoken cancellationtoken)" } 

you can create message handler check content type of request in pipeline , return 415 status code empty body if request content type not supported:

public class unsupportedcontenttypehandler : delegatinghandler {     private readonly mediatypeheadervalue[] supportedcontenttypes =     {         new mediatypeheadervalue("application/json")     };      protected async override task<httpresponsemessage> sendasync(         httprequestmessage request, cancellationtoken cancellationtoken)     {         var contenttype = request.content.headers.contenttype;         if (contenttype == null || !supportedcontenttypes.contains(contenttype))             return request.createresponse(httpstatuscode.unsupportedmediatype);          return await base.sendasync(request, cancellationtoken);     } } 

add message handler message handlers of http configuration (at webapiconfig):

config.messagehandlers.add(new unsupportedcontenttypehandler()); 

and empty responses requests didn't provide content type or have unsupported content type.

note can supported media types global configuration (to avoid duplicating data):

public unsupportedcontenttypehandler() {     supportedcontenttypes = globalconfiguration.configuration.formatters                                 .selectmany(f => f.supportedmediatypes).toarray(); } 

Comments