CORS cross-origin request C,
1. What is a cross-origin problem:
Cross-origin problems may occur when website A uses AJAX to request website B.
At this time, website B can receive A request from website A and return the corresponding results. However, when the browser obtains the data returned by website B, it detects that the domain name of website B is different from that of the current website, for security reasons, the browser will not pass the data to this AJAX request of website.
2. How to solve cross-origin problems:
The cross-origin issue is no longer a new issue. The predecessors have summarized the following methods:
CORS, JSONP, flash, iframe, xhr2, etc.
However, the author prefers to use the CORS method to solve this problem, because the principle of this solution is very simple, you only need to send a response header by the server.
Headers. Add ("Access-Control-Allow-Origin", origin );
3. Code:
Encapsulate a filter to process Http requests
[AttributeUsage (AttributeTargets. method | AttributeTargets. class | AttributeTargets. all, Inherited = true, AllowMultiple = true)] public class corsattriple: ActionFilterAttribute, IActionFilter {// <summary> /// constructor // </summary> /// <param name = "AllowOriginsPattern"> </param> public corsattritern (string allowOriginsPattern = "") {if (string. isNullOrEmpty (allowOriginsPattern) {this. allowOri GinsPattern = ConfigurationManager. appSettings ["AllowOriginsPattern"]. toString ();} else {this. allowOriginsPattern = allowOriginsPattern ;}/// <summary> // the access is complete, append head /// </summary> /// <param name = "filterContext"> </param> public override void OnResultExecuted (ResultExecutedContext filterContext) {try {base. onResultExecuted (filterContext); GetResponse ();} catch (Exception exception) {Htt PContext. current. response. clear (); HttpContext. current. response. write (exception. message); HttpContext. current. response. end () ;}/// <summary> /// allowed regular expression /// </summary> public string AllowOriginsPattern {get; set ;} /// <summary> /// obtain response /// </summary> /// <returns> </returns> public HttpResponse GetResponse () {HttpRequest request = HttpContext. current. request; IDictionary <string, strin G> headers; bool IsEvaluate = TryEvaluate (HttpContext. current. request, out headers); if (IsEvaluate) {foreach (var item in headers) {HttpContext. current. response. headers. add (item. key, item. value) ;}} return HttpContext. current. response ;} /// <summary> /// match? // </summary> /// <param name = "request"> </param> /// <param name = "headers"> </param> // <returns> </returns> public bool TryEvaluate (Ht TpRequest request, out IDictionary <string, string> headers) {headers = null; if (request. Headers. GetValues ("Origin ")! = Null) {string origin = request. headers. getValues ("Origin "). first (); Regex regex = new Regex (AllowOriginsPattern, RegexOptions. ignoreCase); if (regex. isMatch (origin) // match regular {headers = this. generateResponseHeaders (request); return true ;}} return false ;} /// <summary> /// generate head /// </summary> /// <param name = "request"> </param> /// <returns> </returns> private IDictionary <string, string> GenerateResponseHeaders (HttpRequest request) {string origin = request. headers. getValues ("Origin "). first (); Dictionary <string, string> headers = new Dictionary <string, string> (); headers. add ("Access-Control-Allow-Origin", origin); headers. add ("Access-Control-Allow-Headers", "x-requested-with, content-type, requesttype, Token"); headers. add ("Access-Control-Allow-Methods", "POST, GET"); return headers ;}}
Use this filter to receive cross-origin requests.
[Cors (". * ")] // This parameter allows any website to request public JsonResult CorsApi () {return Json (new {data =" "}, JsonRequestBehavior. allowGet );}
You can also add AllowOriginsPattern to the configuration file to control the sites that can request the modification method. In this case, replace the filter with [Cors] on the method.
<appSettings> <add key="AllowOriginsPattern" value="(http://)?(localhost:20735)"/> </appSettings>
4. Of course, there is no cross-origin issue if you request APIs from other websites through the background.
public ActionResult About() { HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create("http://localhost:20735/home/CorsApi"); var reader = new StreamReader(http.GetResponse().GetResponseStream(), Encoding.UTF8).ReadToEnd(); ViewBag.result = reader; return View(); }
Please indicate the source of this original article