2

I'm trying to retrieve a JSON result from a WEB API call.

My WEP API method:

[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;
    }

I have modified the WebapiConfig.cs as below, so that it will always return 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);

Below is my Jquery ajax call:

<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>

It's always end up in error alert. no data is received from the WEB API. I tried debugging and found that my request successfully hits the WEB API method and return JSON. Below is the JSON data it returns.

{"listOfItems":[{"id":14,"description":"New 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}

why am i not getting any result on client side?

6
  • I think it's because you are only returning the Json Data not including the JsonRequestBehavior making it not work on get request? Commented Nov 4, 2013 at 5:53
  • @WannaCSharp i tried with return new System.Web.Mvc.JsonResult() { Data = jsonResult.Data, JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet }; but did not work Commented Nov 4, 2013 at 6:09
  • Can you try looking at the browser console if it gives any errors? Commented Nov 4, 2013 at 6:11
  • i get "XMLHttpRequest cannot load localhost:6606/api/values/Get. Origin localhost:7599 is not allowed by Access-Control-Allow-Origin." error but i think it's ignorable because my POST request worked even thogh i got that error Commented Nov 4, 2013 at 6:17
  • 2
    I would hesitate to ignore that error. It's a pretty clear CORS problem, you need to setup your WebAPI to return the correct CORS headers. stackoverflow.com/questions/19762027/ajax-jquery-request-with-web-api Commented Nov 4, 2013 at 9:32

1 Answer 1

3

I solved the issue by adding Access-Control-Allow-Origin to response header

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.