Asp.net web api2.0 ajax cross-origin solution, api2.0ajax

Source: Internet
Author: User

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 );}}

 

  • Register JsonpMediaTypeFormatter in Global. asax
  • GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.