我正在尝试从WEB API调用中检索JSON结果。
我的WEP API方法:
[AcceptVerbs("GET", "POST")]
public object GetTest()
{
rep = new ChatRepository();
chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);
System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
{
Data = box,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
return jsonResult.Data;
}
我已经如下修改了WebapiConfig.cs,因此它将始终返回JSON
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
以下是我的Jquery ajax调用:
<script type='text/javascript'>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://localhost:6606/api/values/GetTest',
dataType: 'json',
crossDomain: true,
success: function (msg) {
alert('success');
},
error: function (request, status, error) {
alert('error');
}
});
});
</script>
总是会出现错误警报。没有从WEB API收到数据。我尝试调试,发现我的请求成功命中了WEB API方法并返回JSON。以下是它返回的JSON数据。
{“ listOfItems”:[{“ id”:14,“ description”:“新测试”,“ display_number”:1},{“ id”:4,“ description”:“可操作”,“ display_number”:2} ,{“ id”:3,“ description”:“ sales”,“ display_number”:3},{“ id”:5,“ description”:“ technical”,“ display_number”:4}],“ reply”: null,“ history”:null,“ Initialhistory”:null,“ Question”:“”,“ chatids”:null,“ displayNum”:null}
为什么我在客户端没有得到任何结果?
我通过在响应标头中添加Access-Control-Allow-Origin解决了该问题
public class CrossDomainActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
bool needCrossDomain = true;
if (needCrossDomain)
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
[AcceptVerbs("GET", "POST")]
[CrossDomainActionFilter]
public object GetTest()
{
rep = new ChatRepository();
chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);
System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
{
Data = box,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
return jsonResult.Data;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句