I am building a textbook .NET WebAPI web service, which is supposed in the most simplistic case receive a GET request and return a JSON array of objects.
But the project also loads NewtonsoftJSON nuget package, and apparently that package re-defines the ApiController
class, so that its Json()
method has a different declaration. The end result is that I get the following compile time error:
How can I protect the declaration of my controller from being re-defined by Newtonsoft?
public class ImmediateInformationController : ApiController
{
public JsonResult Get([FromUri] ImmediateInformation ii)
{
// some code here
return this.Json(iil, JsonRequestBehavior.AllowGet);
}
}
A bit of a background: initially I was returning just iil
, but when testing in the browser, it prompted to download ImmediateInformation.json
file, which contained the JSON I needed. The above was an attempt to have the JSON returned as plain text, and that lead me to the discovery that Newtonsoft re-defined ApiController
when parameter types did not match MSDN documentation.
Just to re-cap: the question is only using JSON download issue to illustrate what I was doing. How can I ensure that when I am declaring the controller class to be a descendant of ApiController
, it is Microsoft's API controller, and not Newtonsoft's?
Web API 2 includes JSON.NET by default, and uses that in its Json() method . Your tutorial probably doesn't target Web API 2, but an earlier version, or MVC instead of Web API .
Either omit the JsonRequestBehavior:
return this.Json(iil);
Or simply return the proper return type and let Web API handle the serialization:
public ImmediateInformation Get([FromUri] ImmediateInformation ii)
{
return ii;
}
Which you could also do using an IHttpActionResult:
public IHttpActionResult Get([FromUri] ImmediateInformation ii)
{
return this.Ok(ii);
}
According to your edit and comment, you're actually looking for How can I convince IE to simply display application/json rather than offer to download it? .
You'll need to fully qualify the parameter.
return this.Json(iil, System.Web.Mvc.JsonRequestBehavior.AllowGet);
Or you can use an alias .
using NJson = Newtonsoft.Json;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.