使用webapi发布数据时出错

时间:2015-06-16 06:36:48

标签: c# asp.net-web-api mediatypeformatter

我创建了webapi,当我使用这个API发布数据时,我遇到了一些问题,我非常厌倦任何人都可以帮助我。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
    JSONData = {
        "CommunityID": "2",
        "QueryDescription": "gopal",
        "CategoryID": "1"

    };


    $.ajax({
        type: 'POST',
        url: '/api/querycontroller',
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(JSONData),

        success: function (data) {
            $("#button").html(data.responseText + "---------");
        },
        error: function (data) {
            $("#button").html(data.status + "---------" + data.responseText + "---------error");

        }
    });

</script>
<label id="button"></label>

------我的控制器在下面。

      [ResponseType(typeof(Query))]
    [HttpPost]
    public HttpResponseMessage Post([FromBody]Query Services)
    {
        HttpResponseMessage response = new HttpResponseMessage();

        try
        {

            Services.CommunityID = UserStatus.GetUserID(User.Identity.Name);
            Services = repository.Add(Services);

            response = Request.CreateResponse(HttpStatusCode.Created, Services);

            // string uri = Url.Route(null, new { id = Services.QueryID });

            //  response.Headers.Location = new Uri(Request.RequestUri, uri);

            return response;
        }
        catch (Exception dd)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

    }

当我发布时没有contentType:&#34; application / json&#34;,然后它显示错误:415 --------- {&#34; Message&#34;:&#34 ;请求实体的媒体类型&#39; application / x-www-form-urlencoded&#39;此资源不支持。&#34;,&#34; ExceptionMessage&#34;:&#34;没有MediaTypeFormatter可用于读取类型&#39;查询&#39;来自媒体类型的内容&#39; application / x-www-form-urlencoded&#39;。&#34;,&#34; ExceptionType&#34;:&#34; System.Net.Http.UnsupportedMediaTypeException&#34; &#34;堆栈跟踪&#34;:&#34;在System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型类型,IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable 1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)&#34;}

0 个答案:

没有答案