用于jsonp跨域返回jsonp
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
//GlobalConfiguration.Configuration.Formatters.Clear(); 清空返回格式
GlobalConfiguration.Configuration.Formatters.Add(new JsonpMediaTypeFormatter());
}
}
public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
{
private string name;
public override void WriteToStream(Type type, object value, Stream writeStream, Encoding effectiveEncoding)
{
byte[] tmp = effectiveEncoding.GetBytes($"{name}(");
if (name != null)
writeStream.Write(tmp, 0, tmp.Length);
base.WriteToStream(type, value, writeStream, effectiveEncoding);
tmp = effectiveEncoding.GetBytes(")");
if (name != null)
writeStream.Write(tmp, 0, tmp.Length);
}
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
KeyValuePair<string, string> callback = request.GetQueryNameValuePairs().FirstOrDefault(_Item => _Item.Key == "callback");
if (callback.Value != null)
name = callback.Value;
return base.GetPerRequestFormatterInstance(type, request, mediaType);
}
```