如果請求到已包含類型Content-Type
頭不是由該服務所支持我的Web API服務進行,它會返回一條信息類似如下的500 Internal Server Error
狀態代碼:當請求具有不受支持的Content-Type時,如何配置由我的ASP.NET Web API服務返回的狀態代碼?
{"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'MyDto' from content with media type 'application/UnsupportedContentType'.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
at System.Web.Http.Controllers.HttpActionBinding.<>c__DisplayClass1.<ExecuteBindingAsync>b__0(HttpParameterBinding parameterBinder)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator`1 enumerator, CancellationToken cancellationToken)"}
我反而建議返回415 Unsupported Media Type
狀態碼,例如,here。
如何配置我的服務來做到這一點?
我已採用此解決方案,但遇到了輕微問題。對於GET請求,代碼仍然運行,並且不會爲'null'content-type(或我的應用程序中的'text/plain')找到Formatter。所以要解決這個問題,我只是簡單地檢查它是否是一個GET請求,如果是這樣,跳過格式化程序檢查... – JTech