不支持的媒体类型 Web API 发布

本文关键字:API 发布 Web 类型 媒体 不支持 | 更新日期: 2023-09-27 17:55:46

我正在使用AngularJS来发布创建Webapi的数据。 它在我的本地系统上工作,但是当我上传到服务器上时,它不起作用并返回错误,不支持的媒体类型。 请帮助我如何解决此问题。

<script>
var app = angular.module('MyApp', []);
app.controller("QueryControllerController", function ($scope, $http) {
    $scope.submit = function () {
        if ($scope.QueryDescription) {
            var product = {
                "QueryDescription": $scope.QueryDescription,
                "CategoryID": $scope.CategoryID
            }
            $http.post('/api/querycontroller', JSON.stringify(product)).
            success(function (data, status, headers, config) {
                alert('Added Successfully' + headers);
                $('#formusers')[0].reset();
            }).
            error(function (data, status, headers, config) {
                alert(status + ", " + data + ", " + headers + "," + config);
            });
        }
    };
}
);

我的 API 控制器代码是:

[ResponseType(typeof(Query))]
    [HttpPost]
    public HttpResponseMessage Post([FromBody]Query Services)
    {
        Services.CommunityID = UserStatus.GetUserID(User.Identity.Name);
        Services = repository.Add(Services);
        var response = Request.CreateResponse<Query>(HttpStatusCode.Created, Services);
        string uri = Url.Route(null, new { id = Services.QueryID });
        response.Headers.Location = new Uri(Request.RequestUri, uri);
        return response;
    }

当我尝试发布时,我收到不受支持的媒体类型响应。

  "Message": "The request entity's media type 'text/plain' is not supported   for this resource."

不支持的媒体类型 Web API 发布

删除 [ResponseType(typeof(Query))] 并使用 ViewModel 类作为参数

[HttpPost]
public HttpResponseMessage Post([FromBody]ProductViewModel product)
{

也。。。

尝试 https://stackoverflow.com/users/1267724/john 建议的方法(在 agunlar 控制器中)作为这篇文章的答案:将内容类型更改为"application/json" POST 方法,RESTful API

在Angular中发布JSON对象非常容易。您需要做的就是:

创建 Javascript 对象

我将使用代码中的确切属性。

var postObject = new Object();
postObject.userId = "testAgent2";
postObject.token = "testAgent2";
postObject.terminalInfo = "test2";
postObject.forceLogin = "false";
Post the object to the API

要将对象发布到 API,您只需要一个简单的 $http.post 功能。见下文:

$http.post("/path/to/api/", postObject).success(function(data){
    //Callback function here.
    //"data" is the response from the server.
});

由于 JSON 是发布到 API 的默认方法,因此无需 以重置它。有关详细信息,请参阅$http快捷方式上的此链接。

特别是关于您的代码,请尝试更改您的保存方法 以包含此简单的 POST 方法。