标签:
1.配置web.config文件
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="*" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" /> </customHeaders> </httpProtocol>
在Web.config的system.webServer配置节下增加配置即可;
2.通过自定义Formatter,自定义JsonpFormatter并继承于JsonMediaTypeFormatter:
public class JsonpFormatter : JsonMediaTypeFormatter { //当请求过来是带有text/javascript时处理JSONP请求 public JsonpFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript")); JsonpParameterName = "callback"; } //查找函数名 public string JsonpParameterName { get; set; } private string JsonpCallbackFunction; public override bool CanWriteType(Type type) { return true; } //重写此方法来捕获请求对象 public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, MediaTypeHeaderValue mediaType) { var formatter = new JsonpFormatter() { JsonpCallbackFunction = GetJsonCallbackFunction(request) }; //运用JSON.NET来序列化自定义 formatter.SerializerSettings.Converters.Add(new StringEnumConverter()); formatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; return formatter; } //重写此方法写入到流并返回 public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext) { if (string.IsNullOrEmpty(JsonpCallbackFunction)) return base.WriteToStreamAsync(type, value, stream, content, transportContext); StreamWriter writer = null; try { writer = new StreamWriter(stream); writer.Write(JsonpCallbackFunction + "("); writer.Flush(); } catch (Exception ex) { try { if (writer != null) writer.Dispose(); } catch { } var tcs = new TaskCompletionSource<object>(); tcs.SetException(ex); return tcs.Task; } return base.WriteToStreamAsync(type, value, stream, content, transportContext) .ContinueWith(innerTask => { if (innerTask.Status == TaskStatus.RanToCompletion) { writer.Write(")"); writer.Flush(); } }, TaskContinuationOptions.ExecuteSynchronously) .ContinueWith(innerTask => { writer.Dispose(); return innerTask; }, TaskContinuationOptions.ExecuteSynchronously) .Unwrap(); } //从查询字符串中获得JSONP Callback回调函数 private string GetJsonCallbackFunction(HttpRequestMessage request) { if (request.Method != HttpMethod.Get) return null; var query = HttpUtility.ParseQueryString(request.RequestUri.Query); var queryVal = query[this.JsonpParameterName]; if (string.IsNullOrEmpty(queryVal)) return null; return queryVal; } }
//加入自定义配置 GlobalConfiguration .Configuration .Formatters .Insert(0, new JsonpFormatter());
3.通过nuget安装Microsoft.AspNet.WebApi.Cors 包
///首先加入全局配置: var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); eg:在需要使用的接口上加入特性标记即可
[EnableCors(origins: "*", headers: "*", methods: "*")] public class HomeController : Controller { //todo }
标签:
原文地址:http://www.cnblogs.com/infovnet/p/5217491.html