使用 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 代码: 网页应用接口文件代码:
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")
相关文章:
- Froogaloop Vimeo API--Can't在就绪事件之外调用API方法
- 问题将 Javascript 数组发送到带有 List
参数的 Web API 方法 - 无法让简单的 SoundCloud javascript api 方法正常工作
- JSON 对象未传递给 Web API 方法
- 使用 Postman 和 Javascript 在 API 方法中查找特定字段
- 使用 ajax 调用异步 Web api 方法
- 在非 IE 浏览器中访问 API 方法
- ColdFusion 10 CFCHART,如何通过JavaScript API方法传递动态变量
- HTTP GET位于客户端调用的api方法内部
- 调用自定义API方法的功能
- 如何使旧的Twitter API方法在ASP.Net网站上工作
- 美元的资源;如何封装API方法
- Youtube API -在IFrame播放器API方法中删除右下角的Youtube徽标
- 要求的事情.当试图从API方法获取用户时,用户是未定义的
- 不能在FB中声明任何东西.api方法
- 获取详细的用户管理的页面在facebook使用fb.api方法
- 不能使用XMLHttpRequest访问Web API方法,但使用Restclient Plugin等
- 如何在javascript中使用RoutePrefix获取Web API方法的有效url
- 如何从呈现程序进程调用Electron API方法
- 从ASP下载文件.. NET Web API方法使用AngularJS