This essay is reproduced in the article, do not laugh
The first step:
Create Jsonpmediatypeformatter
Public classJsonpmediatypeformatter:jsonmediatypeformatter { Public stringCallback {Get;Private Set; } PublicJsonpmediatypeformatter (stringcallback =NULL) { This. Callback =callback; } Public OverrideTask writetostreamasync (Type type,Objectvalue, Stream writestream, httpcontent content, TransportContext transportcontext) { if(string. IsNullOrEmpty ( This. Callback)) {return Base. Writetostreamasync (type, value, Writestream, content, TransportContext); } Try { This. WriteToStream (type, value, writestream, content); returnTask.fromresult<asyncvoid> (Newasyncvoid ()); } Catch(Exception Exception) {TaskCompletionSource<AsyncVoid> Source =NewTaskcompletionsource<asyncvoid>(); Source. SetException (Exception); returnsource. Task; } } Private voidWriteToStream (Type type,Objectvalue, Stream writestream, httpcontent content) {Jsonserializer Serializer= Jsonserializer.create ( This. Serializersettings); using(StreamWriter StreamWriter =NewStreamWriter (Writestream, This. Supportedencodings.first ()))using(JsonTextWriter JsonTextWriter =NewJsonTextWriter (streamWriter) {closeoutput =false}) {Jsontextwriter.writeraw ( This. Callback +"("); Serializer. Serialize (jsontextwriter, value); Jsontextwriter.writeraw (")"); } } Public Overridemediatypeformatter getperrequestformatterinstance (type type, httprequestmessage request, Mediatypeheadervalue MediaType) {if(Request. Method! =httpmethod.get) {return This; } stringcallback; if(Request. Getquerynamevaluepairs (). ToDictionary (pair =pair. Key, Pair= = Pair. Value). TryGetValue ("Callback", outcallback)) { return NewJsonpmediatypeformatter (callback); } return This; } [StructLayout (LayoutKind.Sequential, Size=1)] Private structasyncvoid {}}
Step Two:
Global.asax Add the following code
protected void Application_Start () {
//Return JSON when used GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear (); // To set the JSONP format serialization method GlobalConfiguration.Configuration.Formatters.Insert (0, new jsonpmediatypeformatter ()); Arearegistration.registerallareas (); Globalconfiguration.configure (webapiconfig.register); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (bundletable.bundles); }
Webapi,webnet receive JSONP