Windows Live Writer 有点问题,着色代码看起来不清晰,所以贴的图片,完整代码在最后。
1:MVC实现
大致思路就是实现一个JsonpResult,在ExecuteResult内实现支持Jsonp,如图
实际上这样就可以在Action内返回JsonpResult对象就可以了。但为了方便起见,也可以添加个拓展。
这样一来我们就可以这样写
前台用ajax调用如下
2:WebApi实现
这里有两种用法,一种是自定义实现一个 JsonpMediaTypeFormatter,另外一种即为Filter
首先是JsonpMediaTypeFormatter,如下
public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter { public string Callback { get; private set; } public JsonpMediaTypeFormatter(string callback = null) { this.Callback = callback; } public override Task WriteToStreamAsync(Type type, object value, 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); return Task.FromResult<AsyncVoid>(new AsyncVoid()); } catch (Exception exception) { TaskCompletionSource<AsyncVoid> source = new TaskCompletionSource<AsyncVoid>(); source.SetException(exception); return source.Task; } } private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings); using (StreamWriter streamWriter = new StreamWriter(writeStream, this.SupportedEncodings.First())) using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter) { CloseOutput = false }) { jsonTextWriter.WriteRaw(this.Callback + "("); serializer.Serialize(jsonTextWriter, value); jsonTextWriter.WriteRaw(")"); } } public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType) { if (request.Method != HttpMethod.Get) { return this; } string callback; if (request.GetQueryNameValuePairs().ToDictionary(pair => pair.Key, pair => pair.Value).TryGetValue("callback", out callback)) { return new JsonpMediaTypeFormatter(callback); } return this; } [StructLayout(LayoutKind.Sequential, Size = )] private struct AsyncVoid { } }
在Global.asax内注册
Controller
此时前端调用任何方法时,只要参数内包含callback即可使用Jsonp调用
然后是Filter方式,实现一个继承自 ActionFilterAttribute 的过滤器JsonpCallbackAttribute
在需要支持Jsonp的方法上加上该Attribute即可
前端调用同上。
3:效果及完整代码
引用:
http://*.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518
http://www.cnblogs.com/artech/archive/2013/12/05/3460544.html
http://www.cnblogs.com/wintersun/archive/2012/05/25/2518572.html
http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-05.html