• WebApi,WebNet 接收Jsonp


    本随笔为文章转载,勿笑

    第一步:

    创建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 = 1)]
            private struct AsyncVoid
            { }
        }

    第二步:

    Global.asax添加以下代码

    protected void Application_Start()
            {
           //返回Json时使用 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    //设置Jsonp格式序列化方法 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); }
  • 相关阅读:
    spring小结2:spring管理bean原理(转帖)
    JAVA Web.xml 加载顺序
    mysql into outfile导出方式
    从平安面试归来
    如何避开求职陷阱
    关注基金走势先~~
    如何谈薪资
    包含数据分析的坐标图测试
    面试题分享
    ShaiShai.net
  • 原文地址:https://www.cnblogs.com/OleRookie/p/5721000.html
Copyright © 2020-2023  润新知