The use of the WEBAPI MVC and the cross-domain problem

Source: Internet
Author: User

In the company often used to call the interface situation, but has been used webservice, I feel really too cumbersome. Although some people feel very good, very cool. For example, when the company is developing, it needs to connect to another set of interfaces, and then it can only specify the port and IP to his computer. All of these problems, he is in the code changes, or the computer does not open, we can not be developed on this side. I want to use the API next time.

Then there are a lot of API articles in the garden that have not dropped to the cross-domain solution, the demo project was created successfully, and then the API's interface method was successfully tuned in the current project. Did it succeed? You kidding us? There is no mistake, is to tease us to play.

Let's go into Webapi and create the WEBAPI project.

Here I have created 2 sites, an API and an MVC project in advance. Then add them separately to IIS (Iis8 here), and if you don't know how to add to IIS I'll simply describe it.

Open IIS Manager-Web site, right-click Add Web Site-name random, physical path Select your Project Web path and then the application pool, best choice defaultapppool--> Hostname: Take a name of your own website (Note: Here the name is required to configure the host file)- -OK

Then is the configuration of the host file,C:\Windows\System32\Drivers\etc Path under the Hosts file, some computers can be directly modified, if you can not copy to the desktop modified and then put in the folder below can be. The configuration is as follows:

127.0.0.1 myweb.loca/
127.0.0.1 myapi.loca/

My web host name: myweb.loca/(same as configuring IIS to name your site)

My API hostname: myapi.loca/(same as configuring IIS to name your site)

When you visit the browser, remember to add:/httpmyweb.loca/

Open API Journey

Then I started to implement the project. The above series of configurations are ready.

First, I'm going to modify the Webapi route, because the default is to determine the method of access based on the argument's pass. Here I set the habit of App_start-->webapiconfig.cs into MVC

           CONFIG. Routes.maphttproute (                "defaultapi",                "api/{ Controller}/{action}/{id}",                new {id = routeparameter.optional}            );    

And then there's a way that the API has been written.

  Public classValuescontroller:apicontroller {PrivateLx. Efopt. Bll. Ibll. IUSER_INFOBLL USER_INFOBLL =NewUSER_INFOBLL (); //GET api/values         Public stringGetList () {List<lx. Efopt. Model.user_info> modeluser_infolist =user_infobll.getuser_infolist (); stringJsonlist =Jsonutils.serializetojson (modeluser_infolist); returnJsonutils.serializetojson (New{Code="1", msg="Success", the data=modeluser_infolist}); }
View Code

Then, we directly in the browser to access the API, verify that our data is correct output, direct access to the address: http://myapi.loca/api/values/GetList

The results are shown below:

Oh, damn, kai-sen! Of course, this is not finished, I did not tease you to play. Next, I'm myweb.loca/this web site to access the API. Walk you ~

Similarly, I have built a user controller on the Web site, and immediately build a Apitest page

<type= "button"  id= "GetList"  value= "Get Data List"  /></>
    function getlist () {        var url = "http://myapi.loca/api/values/GetList?callback=?" ;

Console.log ("Getjson:start");
$.getjson (URL,
function (data) {
Process data
Console.log ("Getjson:end");
Console.log ($.parsejson (data));
});

}

Return Result: No callback function executed

The problem is difficult to find for the first time. Ajax has been executed and the state is 200, and the string returned by response can be seen inside the network. In summary, the return result is not executed in the $.getjson callback function.

The first of these solutions

1, we first come to a low-cost (low-version) solution. Because this version requires only the framework 4.0, you can

Let's add a Jsoncallbackattribute attribute class under the App_start folder to inherit from ActionFilterAttribute. Look at the code, this code is based on the parameters passed over the callback judgment

  Public classJsoncallbackattribute:actionfilterattribute {Private Const stringCallbackqueryparameter ="Callback";  Public Override voidonactionexecuted (Httpactionexecutedcontext context) {varcallback =string.            Empty; if(Isjsonp ( outcallback)) {                varJsonbuilder =NewStringBuilder (callback); Jsonbuilder.appendformat ("({0})", context. Response.Content.ReadAsStringAsync ().                Result); Context. Response.content=Newstringcontent (jsonbuilder.tostring ()); }            Base.        onactionexecuted (context); }        Private BOOLISJSONP ( out stringcallback) {Callback=Httpcontext.current.request.querystring[callbackqueryparameter]; return!string.        IsNullOrEmpty (callback); }    }
View Code

Then add this [Jsoncallback] attribute to the API method above or to the controller.

    [Jsoncallback]      publicclass  valuescontroller:apicontroller         or      [jsoncallback]        publicstring  GetList ()        {        }

Now let's look at what happens after Ajax execution.

added [Jsoncallback] results : It was clear that the callback was successful. And it prints out JSON, which represents the success of our program. Oh, good.

Second Solution

The cost of this approach can be high, at least in the framework of more than 4.5 of the version. Afraid of what. You can have one. Yes, but the average server has 4.5 on it? We don't have it anyway.

The first step: Add a Jsonpmediatypeformatter class below the App_start folder in the API site

      Public classJsonpmediatypeformatter:jsonmediatypeformatter { Public stringCallback {Get;Private Set; }  PublicJsonpmediatypeformatter (stringcallback =NULL)        {             This. Callback =callback; }         Public OverrideTask writetostreamasync (Type type,Objectvalue, Stream writestream, httpcontent content, System.Net.TransportContext transportcontext) {            if(string. IsNullOrEmpty ( This. Callback)) {return Base.            Writetostreamasync (type, value, Writestream, content, TransportContext); }            Try            {                 This.                WriteToStream (type, value, writestream, content); returnTask.fromresult<asyncvoid> (Newasyncvoid ()); }            Catch(Exception Exception) {TaskCompletionSource<AsyncVoid> Source =NewTaskcompletionsource<asyncvoid>(); Source.                SetException (Exception); returnsource.            Task; }        }        Private voidWriteToStream (Type type,Objectvalue, Stream writestream, httpcontent content) {Jsonserializer Serializer= Jsonserializer.create ( This.            Serializersettings); using(StreamWriter StreamWriter =NewStreamWriter (Writestream, This. Supportedencodings.first ()))using(JsonTextWriter JsonTextWriter =NewJsonTextWriter (streamWriter) {closeoutput =false}) {Jsontextwriter.writeraw ( This. Callback +"("); Serializer.                Serialize (jsontextwriter, value); Jsontextwriter.writeraw (")"); }        }         Public Overridemediatypeformatter getperrequestformatterinstance (type type, httprequestmessage request, Mediatypeheadervalue MediaType) {if(Request. Method! =httpmethod.get) {return  This; }            stringcallback; if(Request. Getquerynamevaluepairs (). ToDictionary (pair =pair. Key, Pair= = Pair. Value). TryGetValue ("Callback", outcallback)) {                return NewJsonpmediatypeformatter (callback); }            return  This; }    }
View Code

The second step: Register the Global in the Application_Start of Global.asax

GlobalConfiguration.Configuration.Formatters.Insert (0new jsonpmediatypeformatter ());

In fact, there is the third and fourth solution, but I have not succeeded in testing, do not know what the reason.

Summarize

This solves the Ajax get data to get the method, as for post, the client's own Ajax first submitted to their own HANDLER.ASHX or controller. Then the interface to submit the API with HttpPost is the same.

Thank you! I hope that the great God can leave a little advice and comments, I began to write articles. Give some encouragement.

Thanks to the great God's article

Reference article: http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html

http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518

Source: http://www.cnblogs.com/lxsweat/

The use of the WEBAPI MVC and the cross-domain problem

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.