ASP. NET Vnext API CORS (cross-domain)

Source: Internet
Author: User
Tags http authentication

Overview

cross-domain resource sharing (CORS ) is a technical specification of a Web browser that defines a way for a website to allow Web pages to access their resources from different domains. This access is prohibited by the same-origin policy. The cors system defines a way for browser and server interaction to determine whether cross-domain requests are allowed. It is a compromise, with greater flexibility, but more secure than simply allowing all these requirements to be made.

Cors sets the site's cross-domain access by setting the HTTP header (header).

Access-control-allow-origin A domain that allows cross-domain access, which can be a list of domains or a wildcard "*".
Access-control-allow-credentials By default, cross-origin requests do not provide credentials (cookies, HTTP authentication, and client SSL certificates, etc.). By setting the Withcredentials property to True, you can specify that a request should send credentials. If the server receives a request with credentials, it responds with the following HTTP header
Access-control-expose-headers a header that needs to be exposed to the client .
Access-control-allow-methods Allowed request methods, separated by commas
Access-control-allow-headers Allow custom headers, separated by commas, case insensitive

Instance Code

Start class

      Public voidconfigureservices (iservicecollection services) {services.            Addmvc (); Services. Configurecors (Options={options. Addpolicy ("allowanysimplerequest", builder=                    {                        //allow full access to the domainBuilder. Allowanyorigin ()//allow all Request methods//Allow all headers//Allow all credentials                            . Allowanymethod (). Allowanyheader ().                    Allowcredentials ();                }); Options. Addpolicy ("Allowspecificorigin", builder={Builder. Allowcredentials (). Withorigins ("http://localhost:57096/")                        //Post only allowed. Withmethods ("POST")                          . Allowanyheader ()//Exposed Headers. Withexposedheaders ("Exposed11","Exposed22");            });            }); }

Controller

[Route ("Cors/[action]")] [Enablecors ("allowanysimplerequest")]     Public classBlogcontroller:controller {[Enablecors ("Allowspecificorigin")]         Publicienumerable<string> getblogcomments (intID) {return New[] {"Comment1","Comment2","Comment3" }; }

1. Create a new MVC program

2. Controller

 Public class Homecontroller:controller    {        //  get:home         Public actionresult Index ()        {            //Add Cookie            Response.Cookies.Add ("HttpCookie" ("111 ")  "2222", Expires = DateTime.Now.AddDays (2)});             return View ();        }    }

View

@{Layout=NULL;}<! DOCTYPE html>"Viewport"Content="Width=device-width"/> <title>Index</title> <script src="~/scripts/jquery-1.10.2.js"></script> <script type="Text/javascript"></script>"Button"Id="Cros"Value="get cross-domain"/> <div id="msg"></div> </div> <script type="Text/javascript">$ (function () {$ ("#cros"). Click (function () {$.ajax ({URL:"http://localhost:49271/Cors/GetBlogComments", type:"POST", Success:function (d) {$ ("#msg"). HTML (d)})});    }); </script></body>

has joined the header to be exposed.

Modify a view to support cross-domain cookies

@{Layout=NULL;}<! DOCTYPE html>"Viewport"Content="Width=device-width"/> <title>Index</title> <script src="~/scripts/jquery-1.10.2.js"></script> <script type="Text/javascript">window.onload=function () {alert (" One"); varXHR =NewXMLHttpRequest (); Xhr.open ("Get","http://localhost:49271/Cors/GetBlogComments",true); Xhr.withcredentials=true;//support for sending cookies across domainsXhr.send (); }   </script>"Button"Id="Cros"Value="get cross-domain"/> <div id="msg"></div> </div> <script type="Text/javascript">$ (function () {$ ("#cros"). Click (function () {$.ajax ({URL:"http://localhost:49271/Cors/GetBlogComments", type:"POST", Success:function (d) {$ ("#msg"). HTML (d)})});    }); </script></body>

A cookie has been obtained.

ASP Vnext & MVC6 Series TutorialsIt's my biggest motivation to get your affirmation.

ASP. NET Vnext API CORS (cross-domain)

Related Article

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.