POSTMAN - 发布请求给出"请求实体的媒体类型' application / json'此资源不支持。"

时间:2018-02-09 13:21:49

标签: angular asp.net-web-api asp.net-web-api2

Web API代码:

[HttpPost]
[ODataRoute("GetCMMAutoForLoggedInUser")]
public IHttpActionResult GetCMMAutoForLoggedInUser(CMMPermissionRequest request)
{
    var data = this.CommonDomain.GetCMMAutoForLoggedInUser(request);

    return Ok(data);
}

在正文I中指定JSON:

{ "EnterPriseId": "prasad.kiran.shigwan",
"LocationLevelId": "5",
"LocationLevelValue": "SZ"
} 

但在POSTMAN工具中低于异常:

{
    "error": {
        "code": "",
        "message": "The request entity's media type 'application/json' is not supported for this resource.",
        "innererror": {
            "message": "No MediaTypeFormatter is available to read an object of type 'CMMPermissionRequest' from content with media type 'application/json'.",
            "type": "System.Net.Http.UnsupportedMediaTypeException",
            "stacktrace": "   at System.Net.Http.HttpContentExtensions.ReadAsAsync\[T\](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
        }
    }
}

请参阅以下截图,来自POSTMAN的json:

enter image description here

1 个答案:

答案 0 :(得分:1)

ASP.Net Web API有几个内置的媒体类型格式化程序,负责从json,xml等序列化/反序列化正文内容。

默认情况下,JSON格式化程序始终处于打开状态,对于ASP.Net Web API 2和ASP.Net Core Web API都是如此。问题的POST对我来说对于默认的ASP.Net Web API项目很好,但是如果在WebApiConfig.Register中删除JSON格式化程序我可以重现您的问题:

config.Formatters.Remove(config.Formatters.JsonFormatter);

看起来您在Web API配置中有类似的代码,可以取消注册JsonFormatter。如果不是这种情况,请在WebApiConfig.Register中设置断点并检查config.Formatters集合中的值是什么。以下是JsonFormatter的默认列表:

enter image description here

如果由于某种原因JsonFormatter在您的案例中丢失,您可以明确注册:

config.Formatters.Add(new JsonMediaTypeFormatter());