使用ajax调用async web api方法

时间:2016-02-14 10:49:17

标签: javascript c# api

如何使用jquery ajax调用async web api方法?

JavaScript代码:

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#代码:

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

                    }

C#代码执行成功但ajax不起作用     我的API代码:       Web API Conf。文件代码:

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控制器代码:

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

请任何人都可以帮助我。我尽我最大的努力,但我无法做到。我失去了几天,但我无法找到任何解决方案。

1 个答案:

答案 0 :(得分:0)

正在使用&#34; async:false&#34;可能这会奏效:

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

自&#34; responseText&#34;是字符串,你应该将其转换为xml:

return ( new window.DOMParser() ).parseFromString(resp, "text/xml")