使用 ajax 调用异步 Web api 方法

本文关键字:api 方法 Web 异步 ajax 调用 使用 | 更新日期: 2023-09-27 18:34:28

如何使用

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 代码: 网页应用接口文件代码:

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

请任何人都可以帮助我。我尽力了,但我做不到。我失去了几天,但我找不到任何解决方案。

使用 ajax 调用异步 Web api 方法

当你使用"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")