If I have a web service (.asmx) and I want it to use Json.NET to serialize all the objects that I return from that web service, is there a way to do that?
In other words, I have a class like this:
[JsonObject(MemberSerialization.OptOut)]
public partial class Person
{
public string FirstName {get; set;}
public string LastName {get; set;}
[JsonIgnore]
public string Password {get; set;}
}
And in my web service, I have this:
[WebMethod]
public Person GetBlahPerson()
{
Person p = new Person();
p.FirstName = "bob";
p.LastName = "smith";
p.Password = "don't tell";
return p;
}
If using jQuery I set the return type to json, it serializes my object to json.
Is it possible to make it use Json.net through a setting in web.config or something similar?
Just JSON -- no. You are only able to redefine the whole IHttpHandlerFactory
using
<add verb="*" path="*.asmx" type="YourScriptHandlerFactory" validate="false"/>
But this will mean that you will need to either fall back to default implementation using reflection, or implement your analog of System.Web.Script.Services
namespace (that is quite large).
I actually did it with reflection fallbacks for other purpose (centralized error handling), so it should be possible, but it requires precision and would be very brittle between .NET releases.
Do you use classic ASP.NET or MVC? If you use MVC, just use a controller, it is so much easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With