As.net WebAPI CORS, open cross-source access, resolve error no ' Access-control-allow-origin ' header is present on the requested resource

Source: Internet
Author: User

By default, AJAX requests have a homologous policy that limits the response of different domain requests.

Example: http://localhost:23160/HtmlPage.html request a different source API Http://localhost:22852/api/values,

What is "Same Origin"?

The same origin if they have identical schemes, hosts, and ports. (RFC 6454)

These the same origin:

    • http://example.com/foo.html
    • http://example.com/bar.html

These URLs have different origins than the previous:

    • http://example.net-Different Domain
    • http://example.com:9000/foo.html-Different Port
    • https://example.com/foo.html-Different Scheme
    • http://www.example.com/foo.html-Different Subdomain

The http://localhost:23160/HtmlPage.html code is as follows:

<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head>    <title></title>    <Scriptsrc= "Scripts/jquery-1.10.2.min.js"></Script>    <Scripttype= "Text/javascript">        $(function () {            $("#Button1"). Click (function() {$.ajax ({URL:"http://localhost:22852/api/values", Success:function(data) {alert (data);            }                });        });    }); </Script></Head><Body>    <inputID= "Button1"type= "button"value= "button" /></Body></HTML>

By debugging we found that the AJAX request successfully sent to the Api,api background breakpoint came, and returned the data, and there is no problem. On the web side, viewing the network, the status state shown is also 200, but the content of the response is empty.

At this point, the viewing console will find an error: XMLHttpRequest cannot load http://localhost:22852/api/values. No ' Access-control-allow-origin ' header is present on the requested resource. Origin ' http://localhost:23160 ' is therefore not allowed access.

Tip the API response header does not have a ' access-control-allow-origin ' header, and the identity can allow source http://localhost:23160 access.

We found that the homologous policy did not prevent the request from being sent, but prevented the response from the same origin request.

How is open access to the specified source?

Microsoft engineers have given a solution that can be solved directly by installing a ready-made package.

1.add the CORS NuGet package. In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager C Onsole. In the Package Manager Console window, type the following command:

Install-package Microsoft. AspNet. WebApi. Cors

This command installs the latest package and updates all dependencies, including the core Web API libraries. User the-version flag to target a specific Version. The CORS package requires Web API 2.0 or later.

2.Open the file App_start/webapiconfig.cs. ADD the following code to the webapiconfig.register method.

usingSystem.Web.Http;namespacewebservice{ Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//Enable Cors CONFIG.            Enablecors (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional}); }    }}

3. Next, add the [enablecors] attribute to the TestController class:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Web.Http;usingSystem.Web.Http.Cors;namespaceserverside.controllers{  [Enablecors (Origins:   "http://localhost:23160", headers: "*", Methods: " *")]     Public classTestcontroller:apicontroller { Publichttpresponsemessage Get () {return NewHttpresponsemessage () {Content=NewStringcontent ("get:test Message")            }; }    }}

After the above 3 steps, after the Web-side call API, successfully get the response content: "Get:test message"

For more information, please refer to: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

I go the detour:

1. May be the cause of VS2013, Microsoft was installed. AspNet. WebApi. After the Cors package, the build succeeds, when it runs, error: Failed to load file or assembly "System.Web.Http" or one of its dependencies. The found assembly manifest definition does not match the assembly reference. I look at it because the quoted version is inconsistent, But the packages and bin are stored in the latest 5.2. Version 3, but the error is not found 5.0.0 version, very strange, 5.0. The 0 version is the pre-installation of the Cors package, and the installation of the Cors package will automatically upgrade the dependent System.web.http to 5.2.3, put l5.0.0 's old The version was deleted. Why do you still report this mistake? And it's strange that In Web. config, there is no DLL reference in the configuration, Package.config, the previous. NET project, the version maintenance of the DLL is in the Web. config, the webapi change the way, that is how to configure it, the Internet did not find the answer, and later I look at my local other API project , the DLL was found to be configured in Web. config. Then try to follow other projects, the configuration root in the Webconfig add Runtime phase config assemblybinding, specify 5.2.3 version of the DLL, successfully resolved the problem, the Web. config code is as follows:

<?XML version= "1.0" encoding= "Utf-8"?><!--For more information on how to configure your ASP. Application, please visit http://go.microsoft.com/fwlink/? linkid=301879 -<Configuration>  <appSettings>  </appSettings>  <system.web>    <compilationDebug= "true"targetframework= "4.5" />    <HttpRuntimetargetframework= "4.5" />  </system.web>  <system.webserver>    <handlers>      <Removename= "extensionlessurlhandler-integrated-4.0" />      <Removename= "Optionsverbhandler" />      <Removename= "Traceverbhandler" />      <Addname= "extensionlessurlhandler-integrated-4.0"Path="*."verb="*"type= "System.Web.Handlers.TransferRequestHandler"Precondition= "integratedmode,runtimeversionv4.0" />    </handlers>  </system.webserver>  <Runtime>    <assemblybindingxmlns= "Urn:schemas-microsoft-com:asm.v1">      <dependentassembly>        <assemblyidentityname= "System.Net.Http.Formatting"PublicKeyToken= "31bf3856ad364e35"Culture= "neutral" />        <BindingRedirectoldversion= "0.0.0.0-5.2.3.0"newversion= "5.2.3.0" />      </dependentassembly>      <dependentassembly>        <assemblyidentityname= "System.Web.Http"PublicKeyToken= "31bf3856ad364e35"Culture= "neutral" />        <BindingRedirectoldversion= "0.0.0.0-5.2.3.0"newversion= "5.2.3.0" />      </dependentassembly>    </assemblybinding>  </Runtime></Configuration>
View Code

2. The above problem solved, forgot to add the configuration in the App_start/webapiconfig.cs, just add the attribute on the controller class, or can not be accessed across the source, think it is me vs where the problem, my version is VS2013, The author is VS2013 Update2, and tries to upgrade. Finally go through the process again, only to find the missing configuration, add the configuration, and finally be able to cross-source request, correctly get the response.

As.net WebAPI CORS, open cross-source access, resolve error no ' Access-control-allow-origin ' header is present on the requested resource

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.