簡體   English   中英

使用Ajax調用異步Web API方法

[英]Call async web api method using ajax

如何使用jquery ajax調用異步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);
        }
    }

請任何人可以幫助我。 我盡我所能,但我做不到。 我失去了幾天,但找不到任何解決方案。

當您使用“ async:false”時,這可能會起作用:

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

由於“ responseText”是字符串,因此應將其轉換為xml:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM