JSON return error with ASP

We use a third-party ASP application. I am tasked with making a small change to the application, but I don't know anything about asp or json. After some research, I put it together. I created a text box on the form, and I want to return the client IP address to this text box. I wrote a function, then a controller. The code for both is below:

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

Controller

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

I get these errors in this line of code:

return Json(ipAddress, JsonRequestBehavior.AllowGet);

The error I get is:

The best overloaded method match for System.Web.Http.ApiController.Json (string, Newtonsoft.Json.JsonSerializerSettings) has some invalid arguments. Unable to convert from System.Web.Mvc.JsonRequestBehavior to Newtonsoft.Json.JsonSerializerSettings

If someone can tell me what they mean and how to fix it, I would really appreciate it.

+8
json c # asp.net-mvc
source share
2 answers

Json in ApiController with two parameters has a signature,

 protected internal JsonResult<T> Json<T>( T content, JsonSerializerSettings serializerSettings ) 

Json in Controller with two parameters has a signature,

 protected internal JsonResult Json( object data, JsonRequestBehavior behavior ) 

getipaddressController inherited from ApiController , but you used the Json controller Json . Use

 return new JsonResult() { Data = ipAddress, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; 

If you still want behavior.

+10
source share

use ActionResult instead of JsonResult

 public ActionResult GetIPAddress() { } 

you can see an example here

0
source share

All Articles