【问题标题】:Ajax Jquery Request with WEB API带有 WEB API 的 Ajax Jquery 请求
【发布时间】:2013-11-14 17:39:06
【问题描述】:

我正在尝试从 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":"新 test","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}

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

【问题讨论】:

  • 我认为这是因为您只返回 Json Data 不包括 JsonRequestBehavior 使其无法在获取请求中工作?
  • @WannaCSharp 我尝试使用 return new System.Web.Mvc.JsonResult() { Data = jsonResult.Data, JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet };但没有工作
  • 如果出现错误,您可以尝试查看浏览器控制台吗?
  • 我得到“XMLHttpRequest 无法加载 localhost:6606/api/values/Get。Access-Control-Allow-Origin 不允许来源 localhost:7599。”错误,但我认为这是可以忽略的,因为即使我收到了该错误,我的 POST 请求仍然有效
  • 我会犹豫忽略该错误。这是一个非常明显的 CORS 问题,您需要设置 WebAPI 以返回正确的 CORS 标头。 stackoverflow.com/questions/19762027/ajax-jquery-request-with-web-api

标签: jquery asp.net-mvc json asp.net-mvc-4 asp.net-web-api


【解决方案1】:

我通过将 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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2014-06-30
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多