ASP. NET Core CORS simple to use

Source: Internet
Author: User

CORS full Name "cross-domain resource sharing" (cross-origin resource sharing).

Cross-domain is the data access between different domains, such as a.sample.com access to the data in b.sample.com, if we do not do any processing, the following error will occur:

XMLHttpRequest cannot load b.sample.com. No ' Access-control-allow-origin ' header is present on the requested resource. Origin ' a.sample.com ' is therefore not allowed access. The response had HTTP status code 404.

Request and Response information:

Response HeadersContent-Type:text/html; charset=utf-8Server:Microsoft-IIS/10.0X-Powered-By:ASP.NETRequest HeadersAccept:*/*Accept-Encoding:gzip, deflateAccept-Language:zh-CN,zh;q=0.8Connection:keep-aliveContent-Length:32384Host:b.sample.comOrigin:a.sample.com

When the request is initiated, host acquires Origin and then determines whether or not it agrees to the request, and the criterion is access-control-allow-origin, if the host server specifies the origin configuration, then the response header will be:

Access-Control-Allow-Origin:a.sample.com

Related access-control-*:

    • Access-control-allow-origin: Specifies whether origin is accessed in the request header and, if the value is *, allows any origin access.
    • access-control-request-method: Allowed HTTP request method, common Get, Post, Put, etc., if the value is *, then all HTTP request method access is allowed.
    • access-control-expose-headers: The client can obtain the Cache-control, Content-language, Content-type, Expires, and the response header from the server by default last-modified, Pragma field information, if additional header field information needs to be obtained, it needs to be configured on the server side.
      Access-control-request-headers: The additional request header information that is allowed to be sent to the server by the client is similar to the above access-control-expose-headers, but the direction is reversed and is typically used to add custom header, such as X-param and so on.
    • access-control-allow-credentials: If the value is true, it means that the server can accept Cookie information sent by the client, but it needs to be set simultaneously in the client request withCredentials = true; .
    • access-control-max-age: The cache time of the request check, that is, for a period of time, the client sends a request to the server, does not need to check the Origin configuration, but the direct request access, of course, except after the server changed configuration.

The above are basic information about cors, and we need to manually configure cors in ASP. NET MVC Application development:

 Public classallowcorsattribute:actionfilterattribute{Private string[] _domains; Public Allowcorsattribute(params string[] domains) {_domains = domains; } Public Override void onactionexecuting(ActionExecutingContext Filtercontext) {varContext = Filtercontext.RequestContext.HttpContext;if(Context.Request.Urlreferrer!=NULL)        {varHost = context.Request.Urlreferrer?.Host;if(Host! =NULL&& _domains.Contains(host)) {context.Response.AddHeader("Access-control-allow-origin", $"Http://{host}"); }        }Else{context.Response.AddHeader("Access-control-allow-origin","*"); } context.Response.AddHeader("Access-control-allow-methods","GET, HEAD, OPTIONS, POST, PUT"); Context.Response.AddHeader("Access-control-allow-headers","Access-control-allow-headers, Origin,accept, X-requested-with, Content-type, Access-control-request-method, Access-control-request-headers ");Base.onactionexecuting(Filtercontext); }}

The above code is to intercept each Action request, the hand movement request context to add the corresponding header configuration to achieve the purpose of CORS, Action configuration:

[AllowCors("a.sample.com", "c.sample.com")]public ActionResult Index(){    return View();}

Configuring CORS in the ASP. NET WebAPI project does not require the complexity of the above, we only need to install:

Install-Package Microsoft.AspNet.WebApi.Cors

Then configure enable CORS:

publicstaticclass WebApiConfig{    publicstaticvoidRegister(HttpConfiguration config)    {        config.EnableCors();        config.Routes.MapHttpRoute(            "DefaultApi",            "api/{controller}/{id}",            new { id = RouteParameter.Optional }        );    }}

Finally, add the CORS configuration on the corresponding Action:

[EnableCors"http://a.sample.com""*""get,post"true)]publicIndex(){    returnView();}

The CORS configuration on the ASP. NET Core is similar to the above, configuration method:

Add Configuration in Configureservices:

publicvoidConfigureServices(IServiceCollection services){    // Add framework services.    services.AddMvc();    services.AddCors(options => options.AddPolicy("CorsSample",        p => p.WithOrigins("http://a.example.com""http://c.example.com").AllowAnyMethod().AllowAnyHeader()));}

Enable configuration in Configure:

publicvoidConfigure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){    app.UseStaticFiles();    app.UseMvc(routes =>    {        routes.MapRoute(            "default",            "{controller=Home}/{action=Index}/{id?}");    });    app.UseCors("CorsSample");}

Action enables the corresponding CORS and is not enabled for use [DisableCors] .

[EnableCors("CorsSample")]publicIndex(){    returnView();}

Of course, the use of CORS in ASP. NET Core is not only here, you can also customize it to see the final reference.

There are other workarounds for cross-domain addition to CORS:

    • JSONP: Only GET requests are supported by embedding a tag in the document <script> to return data from another domain, but using the simpler, data: ASP. NET Web API configuration JSONP
    • Document.domain:JS Configuration Code document.domain = ‘sample.com’; , set up, the same domain can be JS to each other access, but there are some hidden dangers, such as a site by JS injected, then will be involved in other sites, information: ASP. NET page prohibited by the IFRAME framework reference

Resources:

    • About CORS
    • Cross-domain resource sharing CORS detailed
    • Enabling Cross-origin requests in ASP. NET Web API 2
    • Enabling Cross-origin requests (CORS)

Reference page:hTTP://QINgQINgQuege.CNbLogs.Com/P/5933752.hTmL

ASP. NET Core CORS simple to use

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.