2

How can I call async web api method using jquery ajax?

JavaScript Code:

var serviceUrl = 'http://localhost:4770/api/values';
                    $.ajax({
                        type: "GET",
                        url: serviceUrl,
                        data: {},
                        async:false,
                        contentType: "text/xml",
                        dataType: "xml",                   
                        success: function (data) {

                        },
                        error: function (data) {

                        }
                    });

C# Code :

using (var client = new HttpClient())
                    {
                        var response = client.GetAsync("http://localhost:4770/api/values").Result;
                        var resultContent = response.Content.ReadAsStringAsync().Result;

                    }

C# code execute successfully but ajax is not work.
My API code: Web API Conf. file Code:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            config.EnableCors();

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            config.Formatters.XmlFormatter.UseXmlSerializer = true;

            GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageLoggingHandler());

            // Web API routes
            config.MapHttpAttributeRoutes();

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


        }
    }

    public abstract class MessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
            var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri);

            var requestMessage = await request.Content.ReadAsByteArrayAsync();


            await IncommingMessageAsync(corrId, requestInfo, requestMessage);

            var response = await base.SendAsync(request, cancellationToken);

            byte[] responseMessage;

            if (response.IsSuccessStatusCode)
                responseMessage = await response.Content.ReadAsByteArrayAsync();
            else
                responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);

            await OutgoingMessageAsync(corrId, requestInfo, responseMessage);



            return response;
        }


        protected abstract Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message);
        protected abstract Task OutgoingMessageAsync(string correlationId, string requestInfo, byte[] message);
    }



    public class MessageLoggingHandler : MessageHandler
    {
        protected override async Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message)
        {
            await Task.Run(() => Debug.WriteLine(string.Format("APP TRACING: {0} - Request: {1}\r\n{2}", correlationId, requestInfo, Encoding.UTF8.GetString(message))));
        }


        protected override async Task OutgoingMessageAsync(string correlationId, string requestInfo, byte[] message)
        {
            await Task.Run(() => Debug.WriteLine(string.Format("APP TRACING: {0} - Response: {1}\r\n{2}", correlationId, requestInfo, Encoding.UTF8.GetString(message))));
        }
    }

API Controller Code:

[EnableCors(origins: "*", headers: "*", methods: "*")]
    [AllowAnonymous]
    public class ValuesController : ApiController
    {
        public IHttpActionResult Get()
        {
            return new DataManager().GetUser();
        }


    }


    public class DataManager
    {
        public IHttpActionResult GetUser()
        {
            var x = "HA HO HE";

            return new HttpActionResult(HttpStatusCode.OK, x);

        }
    }

    public class HttpActionResult : IHttpActionResult
    {
        private readonly string _message;
        private readonly HttpStatusCode _statusCode;

        public HttpActionResult(HttpStatusCode statusCode, string message)
        {
            _statusCode = statusCode;
            _message = message;
        }


        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage(_statusCode)
            {
                Content = new StringContent(_message)
            };
            return Task.FromResult(response);
        }
    }

Please any one can help me. I try my level best but i can't do it. I lost my couple of days but i can't find any solution.

1 Answer 1

1

As you are using "async:false" probably this would work:

 var resp = $.ajax({
                    type: "GET",
                    url: 'http://localhost:4770/api/values',
                    async:false,
                    contentType: "text/xml",
                    dataType: "xml"
                }).responseText;

Since "responseText" is string you should convert it to xml:

return ( new window.DOMParser() ).parseFromString(resp, "text/xml")
Sign up to request clarification or add additional context in comments.

2 Comments

When i use this config.Formatters.XmlFormatter.UseXmlSerializer = true; in webapi.config it automatically convert to xml.
@SumonBanerjee Hi. I know. In this situation you have an XML document that is sent to you as string datatype. If you need to treat it as XMLDocument in javascript you should convert it; If you don't, you have and string datatype which the content is XML...Anyway, did it work?

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.