1. Create a Web API (myservice.azurewebsites.net)
This simply puts:
1.1
1.2
1.3
1.4
1.5
1.6 Replace the following code with the original TestController
usingSystem.Net.Http;usingSystem.Web.Http;namespacewebservice.controllers{ Public classTestcontroller:apicontroller { Publichttpresponsemessage Get () {return NewHttpresponsemessage () {Content=NewStringcontent ("get:test Message") }; } Publichttpresponsemessage Post () {return NewHttpresponsemessage () {Content=NewStringcontent ("post:test Message") }; } Publichttpresponsemessage Put () {return NewHttpresponsemessage () {Content=NewStringcontent ("put:test Message") }; } }}
1.7 You can test whether the Web API you are creating works
2. Create client side (myclilent.azurewebsites.net)
This can also be simple:
2.1
2.2
2.3 Locate the client side of the views/home/index.cshtml and replace it with the following code
<div> <SelectId="Method"> <option value="Get">GET</option> <option value="Post">POST</option> <option value="put">PUT</option> </Select> <input type="Button"Value="Try It"onclick="SendRequest ()"/> <span id='value1'> (Result) </span></div>@section Scripts {<script>varserviceurl ='http://myservice.azurewebsites.net/api/test';//Replace with your URI.function SendRequest () {varMETHOD = $ ('#method'). Val (); $.ajax ({type:method, url:serviceurl}). Done (function (data) {$ ('#value1'). text (data); }). Error (Function (JQXHR, textstatus, Errorthrown) {$ ('#value1'). Text (Jqxhr.responsetext | |textstatus); }); }</script>}
2.4 With the exception of a domain name publishing site, and then go to the index page, select Get,post,put, and so on, click the Try it button, will send the request to the Web API, because the Web API does not open cors, and through the AJAX request, the browser will prompt error
3.Web API Support Cors
3.1 Open vs, tools---Library Package Manager, Package Manager console , enter the following command:install-package Microsoft.AspNet.WebApi.Cors- Version 5.0.0
Note: Currently nuget above the latest version is 5.2.0, but I test, download, there will be some associated class library is not up-to-date, System.Net.Http.Formatting requirements is 5.2, I find this DLL on the Internet, so it is recommended to install : Microsoft.AspNet.WebApi.Cors 5.0 is OK.
Nuget Popular link:http://www.cnblogs.com/dubing/p/3630434.html
3.2 Open webapiconfig.register Add config. Enablecors ()
usingSystem.Web.Http;namespacewebservice{ Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//New CodeCONFIG. Enablecors (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional}); } }}
3.3 Adding [enablecors] attributes to TestController
usingSystem.Net.Http;usingSystem.Web.Http;usingSystem.Web.Http.Cors;namespacewebservice.controllers{[Enablecors (Origins:"http://myclient.azurewebsites.net", headers:"*", Methods:"*")] Public classTestcontroller:apicontroller {//Controller methods not shown ... }}
3.4 Back to the client side, then send the request again, will prompt the success of information, to prove that Cors has been implemented.
4. Set [Enablecors] to Action, Controller, globally
4.1Action
Public classitemscontroller:apicontroller{ Publichttpresponsemessage GetAll () {...} [Enablecors (Origins:"http://www.example.com", headers:"*", Methods:"*")] PublicHttpresponsemessage GetItem (intID) {...} Publichttpresponsemessage Post () {...} PublicHttpresponsemessage PutItem (intID) {...}}
4.2Controller
[Enablecors (Origins:"http://www.example.com", headers:"*", Methods:"*")] Public classitemscontroller:apicontroller{ Publichttpresponsemessage GetAll () {...} PublicHttpresponsemessage GetItem (intID) {...} Publichttpresponsemessage Post () {...} [Disablecors] PublicHttpresponsemessage PutItem (intID) {...}}
4.3Globally
Public Static classwebapiconfig{ Public Static voidRegister (httpconfiguration config) {varCors =NewEnablecorsattribute ("www.example.com","*","*"); Config. Enablecors (cors); // ... }}
5.[enablecors] how it works
To understand the principle of cors success, we can look at
Cross-Domain requests
GET http://myservice.azurewebsites.net/api/test http/1.1referer:http:// myclient.azurewebsites.net/Accept: */*http://myclient.azurewebsites.net Accept-encoding:gzip, deflateuser-agent:mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; trident/6.0) Host:myservice.azurewebsites.net
When the request is sent, the browser sends the "Origin" request hair to the server, if the server allows cross-domain requests, then responds back to the request header, adding " Access-control-allow-origin", and add the value of the requested domain name to the access-control-allow-origin, the browser receives the request header, The returned data is displayed, otherwise the browser will not receive the data even if the server has successfully returned
Response of the server
http/1.1 okcache-control:no-cachepragma:no-cachecontent-type: Text/plain; charset=utf-8Access-control-allow-origin:http://myclient.azurewebsites.net to - : $ gmtcontentget:test message
6. Custom Cors Policy Providers
6.1 In addition to using the [enablecors] feature, we can customize our own [enablecors]. The first is to inherit the Attribute and Icorspolicyprovider interfaces
[AttributeUsage (AttributeTargets.Method | AttributeTargets.Class, AllowMultiple =false)] Public classMycorspolicyattribute:attribute, Icorspolicyprovider {PrivateCorspolicy _policy; PublicMycorspolicyattribute () {//Create a CORS policy._policy =NewCorspolicy {Allowanymethod=true, Allowanyheader=true }; //Add allowed origins._policy. Origins.add ("http://myclient.azurewebsites.net"); _policy. Origins.add ("http://www.contoso.com"); } PublicTask<corspolicy>Getcorspolicyasync (Httprequestmessage request) {returnTask.fromresult (_policy); }}
Once implemented, you can add your own defined [mycorspolicy]
[Mycorspolicy] Public class testcontroller:apicontroller{ //
6.2 or you can read the allowed domain name from the configuration file
Public classcorspolicyfactory:icorspolicyproviderfactory{Icorspolicyprovider _provider=NewMycorspolicyprovider (); PublicIcorspolicyprovider Getcorspolicyprovider (httprequestmessage request) {return_provider; }} Public Static classwebapiconfig{ Public Static voidRegister (httpconfiguration config) {config. Setcorspolicyproviderfactory (Newcorspolicyfactory ()); Config. Enablecors (); // ... }}
Let the ASP. NET Web API support cors through the Microsoft Cors Class Library