chamara
chamara

Reputation: 12711

Ajax Jquery Request with WEB API

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?

Upvotes: 2

Views: 5159

Answers (1)

chamara
chamara

Reputation: 12711

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

Upvotes: 3

Related Questions