Asp.net web api2.0 ajax cross-origin solution, api2.0ajax
I did not talk about the advantages and disadvantages of Web APIs. I directly talked about cross-origin. I searched for two methods.
I. ASP. NET Web APIs support JSONP in two ways
1, using JsonMediaTypeFormatter, specific reference here: http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html
Code:
Create a JsonpMediaTypeFormatter class:
Public class JsonpMediaTypeFormatter: JsonMediaTypeFormatter {private string callbackQueryParameter; public JsonpMediaTypeFormatter () {SupportedMediaTypes. add (defamedimediatype); SupportedMediaTypes. add (new MediaTypeHeaderValue ("text/javascript"); MediaTypeMappings. add (new UriPathExtensionMapping ("jsonp", DefaultMediaType);} public string CallbackQueryParameter {get {return callbackQueryPara Meter ?? "Callback" ;}set {callbackQueryParameter = value ;}} /// <summary> /// fill in the serialized JSON string of the object to the JavaScript callback function. /// </summary> /// <param name = "type"> </param> /// <param name = "value"> </param> /// <param name = "stream"> </param> /// <param name = "content"> </param> /// <param name = "transportContext"> </param> /// <returns> </returns> public override Task WriteToStreamAsync (Type type, object value, Stream str Eam, HttpContent content, TransportContext transportContext) {string callback; if (IsJsonpRequest (out callback) {return Task. factory. startNew () => {var writer = new StreamWriter (stream); writer. write (callback + "("); writer. flush (); base. writeToStreamAsync (type, value, stream, content, transportContext ). wait (); writer. write (")"); writer. flush () ;}) ;}else {return base. writeToStreamAsync (typ E, value, stream, content, transportContext );}} /// <summary> /// determine whether the request is a cross-origin request // </summary> /// <param name = "callback"> </param> // <returns> </returns> private bool IsJsonpRequest (out string callback) {callback = null; if (HttpContext. current. request. httpMethod! = "GET") return false; callback = HttpContext. Current. Request. QueryString [CallbackQueryParameter]; return! String. IsNullOrEmpty (callback );}}
2, using ActionFilterAttribute, specific reference here: http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518
Code:
Create a JsonCallbackAttribute class
public class JsonCallbackAttribute : ActionFilterAttribute { private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var callback = string.Empty; if (IsJosnp(out callback)) { var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", actionExecutedContext.Response.Content.ReadAsStringAsync().Result); actionExecutedContext.Response.Content = new StringContent("C(\"a\")"); } base.OnActionExecuted(actionExecutedContext); } private bool IsJosnp(out string callback) { callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); } }
Register JsonCallbackAttribute in Global. asax
GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());
2. Use Microsoft ASP. NET Web API 2 Cross-Origin Suppor
Install Microsoft ASP. NET Web API 2 Cross-Origin Support using NuGe.
EnableCors supports CORS in Global. asax.
Test instance:
<! DOCTYPE html>
When a Ajax request Post data, you must add the following items:
contentType: 'application/json; charset=utf-8',data: JSON.stringify(user),
In this way, I just sorted out the solutions on the network and put them all.