ASP的JSON返回错误
我们正在使用由外部供应商编写的ASP应用程序。 我的任务是对应用程序进行一些小改动但是我对asp或json一无所知。 通过一些研究,我把它放在一起。 我在表单上创建了一个文本框,我想将客户端IP地址返回到该文本框。 我写了一个函数然后一个控制器。 两者的代码如下:
function
function processgetip(event) { // Within this function, make an AJAX call to get the IP Address $.getJSON('@Url.Action("GetIPAddress","getipaddress")', function (ip) { // When this call is done, your IP should be stored in 'ip', so // You can use it how you would like // Example: Setting a TextBox with ID "YourElement" to your returned IP Address $("#facility").val(ip); }); }
控制器
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using System.Web.Mvc; namespace Parker_Hannifin.Controllers { public class getipaddressController : ApiController { public JsonResult GetIPAddress() { System.Web.HttpContext context = System.Web.HttpContext.Current; string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { string[] addresses = ipAddress.Split(','); if (addresses.Length != 0) { //return addresses[0]; // ipAddress = addresses[0]; } } //replace ipaddress with ipAddress return Json(ipAddress, JsonRequestBehavior.AllowGet); } } }
我在这行代码中遇到这些错误:
return Json(ipAddress, JsonRequestBehavior.AllowGet);
我得到的错误是:
System.Web.Http.ApiController.Json(字符串,Newtonsoft.Json.JsonSerializerSettings)的最佳重载方法匹配具有一些无效参数。 无法从System.Web.Mvc.JsonRequestBehavior转换为Newtonsoft.Json.JsonSerializerSettings
如果有人可以请告诉我他们的意思以及如何解决这些问题我会非常感激。
带有两个参数的ApiController
Json
有一个签名,
protected internal JsonResult Json ( T content, JsonSerializerSettings serializerSettings )
带有两个参数的Controller
Json
有一个签名,
protected internal JsonResult Json( object data, JsonRequestBehavior behavior )
getipaddressController
inheritance自ApiController
,但您使用的是Controller方法Json
。 使用,
return new JsonResult() { Data = ipAddress, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
如果你仍然想要这种行为。
使用ActionResult
而不是JsonResult
public ActionResult GetIPAddress() { }
你可以在这里看到一个例子