2

我正在尝试从 WEB API 调用中检索 JSON 结果。

我的 WEP API 方法:

[AcceptVerbs("GET", "POST")]
    public object GetTest()
    {
         rep = new ChatRepository();
        chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);

        System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
        {
            Data = box,
            JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
        };


        return jsonResult.Data;
    }

我已将 WebapiConfig.cs 修改如下,使其始终返回 JSON

 config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{action}/{id}",
          defaults: new { action = "get", id = RouteParameter.Optional }
          );

            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

下面是我的 Jquery ajax 调用:

<script type='text/javascript'>

    $(document).ready(function () {

        $.ajax({
            type: 'GET',
            url: 'http://localhost:6606/api/values/GetTest',

            dataType: 'json',

            crossDomain: true,
            success: function (msg) {

                alert('success');

            },
            error: function (request, status, error) {

                alert('error');
            }
        });
    });

</script>

它总是以错误警报告终。未从 WEB API 接收数据。我尝试调试,发现我的请求成功命中WEB API方法并返回JSON。下面是它返回的 JSON 数据。

{"listOfItems":[{"id":14,"description":"新测试","display_number":1},{"id":4,"description":"operational","display_number":2} ,{"id":3,"description":"sales","display_number":3},{"id":5,"description":"technical","display_number":4}],"reply": null,"history":null,"Initialhistory":null,"Question":"","chatids":null,"displayNum":null}

为什么我在客户端没有得到任何结果?

4

1 回答 1

3

我通过将 Access-Control-Allow-Origin 添加到响应标头解决了这个问题

public class CrossDomainActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            bool needCrossDomain = true;

            if (needCrossDomain)
            {
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }

            base.OnActionExecuted(actionExecutedContext);
        }
    }


[AcceptVerbs("GET", "POST")]
[CrossDomainActionFilter]
    public object GetTest()
    {
         rep = new ChatRepository();
        chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);

        System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
        {
            Data = box,
            JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
        };


        return jsonResult.Data;
    }
于 2013-11-04T09:55:36.830 回答