ASP. NET API Count

Source: Internet
Author: User

1. Control returns only JSON one data

         Public classJsoncontentnegotiator:icontentnegotiator {Private ReadOnlyJsonmediatypeformatter _jsonformatter;  PublicJsoncontentnegotiator (Jsonmediatypeformatter formatter) {_jsonformatter=formatter; }             PublicContentnegotiationresult Negotiate (type type, httprequestmessage request, ienumerable<mediatypeformatter>formatters) {                varresult =NewContentnegotiationresult (_jsonformatter,NewMediatypeheadervalue ("Application/json")); returnresult; }        }

Use: In WebApiConfig.cs

  Public Static voidRegister (httpconfiguration config) {config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{action}", defaults:New{id =routeparameter.optional}); //uncomment the following line of code to enable query support for operations that have a IQueryable or iqueryable<t> return type. //to avoid handling unexpected queries or malicious queries, use the validation settings on Queryableattribute to validate incoming queries. //For more information, please visithttp://go.microsoft.com/fwlink/?LinkId=279712. //CONFIG.            Enablequerysupport (); //to disable tracing in your application, comment out or delete the following line of code//For more information, see:Http://www.asp.net/web-apiCONFIG.            Enablesystemdiagnosticstracing (); var jsonformatter = new Jsonmediatypeformatter (); Optional:set serializer settings here config. Services.replace (typeof (Icontentnegotiator), new Jsoncontentnegotiator (jsonformatter)); }

2. Support cross-domain post, many online are. NET 4.5, find a way to find. NET 4.0 for a long time

 Public classCorshandler:delegatinghandler {Const stringOrigin ="Origin"; Const stringAccesscontrolrequestmethod ="Access-control-request-method"; Const stringAccesscontrolrequestheaders ="access-control-request-headers"; Const stringAccesscontrolalloworigin ="Access-control-allow-origin"; Const stringAccesscontrolallowmethods ="Access-control-allow-methods"; Const stringAccesscontrolallowheaders ="access-control-allow-headers"; protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) {BOOLIscorsrequest =request.                Headers.contains (Origin); BOOLIspreflightrequest = Request. Method = =httpmethod.options; if(iscorsrequest) {if(ispreflightrequest) {returnTask.factory.startnew{httpresponsemessage response=Newhttpresponsemessage (Httpstatuscode.ok); Response. Headers.add (Accesscontrolalloworigin, request.) Headers.getvalues (Origin).                            First ()); stringAccesscontrolrequestmethod =request. Headers.getvalues (Accesscontrolrequestmethod).                            FirstOrDefault (); if(Accesscontrolrequestmethod! =NULL) {Response.                            Headers.add (Accesscontrolallowmethods, Accesscontrolrequestmethod); }                            stringRequestedheaders =string. Join (", ", request.                            Headers.getvalues (accesscontrolrequestheaders)); if(!string. IsNullOrEmpty (requestedheaders)) {response.                            Headers.add (Accesscontrolallowheaders, requestedheaders); }                            returnresponse;                    }, CancellationToken); }                    Else                    {                        return Base. SendAsync (Request, CancellationToken). Continuewith{Httpresponsemessage resp=T.result; Resp. Headers.add (Accesscontrolalloworigin, request.) Headers.getvalues (Origin).                            First ()); returnresp;                    }); }                }                Else                {                    return Base.                SendAsync (Request, CancellationToken); }            }        }

Use: In Global.asax

        protected void Application_Start ()        {            arearegistration.registerallareas ();            Webapiconfig.register (globalconfiguration.configuration);            Filterconfig.registerglobalfilters (globalfilters.filters);            Routeconfig.registerroutes (routetable.routes);            Bundleconfig.registerbundles (bundletable.bundles);            GlobalConfiguration.Configuration.MessageHandlers.Add (   New Corshandler ());             New gzframeworkdbconfig ();        }

ASP. NET API Count

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.