ASP.NET API盤點

來源:互聯網
上載者:User

標籤:

1.控制只返回JSON一種資料

        public class JsonContentNegotiator : IContentNegotiator        {            private readonly JsonMediaTypeFormatter _jsonFormatter;            public JsonContentNegotiator(JsonMediaTypeFormatter formatter)            {                _jsonFormatter = formatter;            }            public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)            {                var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));                return result;            }        }

使用:在WebApiConfig.cs中

 public static void Register(HttpConfiguration config)        {            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{action}",                defaults: new { id = RouteParameter.Optional }            );            // 取消注釋下面的程式碼可對具有 IQueryable 或 IQueryable<T> 傳回型別的操作啟用查詢支援。            // 若要避免處理意外查詢或惡意查詢,請使用 QueryableAttribute 上的驗證設定來驗證傳入查詢。            // 有關詳細資料,請訪問 http://go.microsoft.com/fwlink/?LinkId=279712。            //config.EnableQuerySupport();            // 若要在應用程式中禁用跟蹤,請注釋掉或刪除以下程式碼            // 有關詳細資料,請參閱: http://www.asp.net/web-api            config.EnableSystemDiagnosticsTracing();            var jsonFormatter = new JsonMediaTypeFormatter();            //optional: set serializer settings here            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));        }

 

 

2.支援跨域POST,網上很多都是.net 4.5的,找了好久才找到.net 4.0的方法

public class CorsHandler : DelegatingHandler        {            const string Origin = "Origin";            const string AccessControlRequestMethod = "Access-Control-Request-Method";            const string AccessControlRequestHeaders = "Access-Control-Request-Headers";            const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";            const string AccessControlAllowMethods = "Access-Control-Allow-Methods";            const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)            {                bool isCorsRequest = request.Headers.Contains(Origin);                bool isPreflightRequest = request.Method == HttpMethod.Options;                if (isCorsRequest)                {                    if (isPreflightRequest)                    {                        return Task.Factory.StartNew<HttpResponseMessage>(() =>                        {                            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);                            response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());                            string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();                            if (accessControlRequestMethod != null)                            {                                response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);                            }                            string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));                            if (!string.IsNullOrEmpty(requestedHeaders))                            {                                response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);                            }                            return response;                        }, cancellationToken);                    }                    else                    {                        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>                        {                            HttpResponseMessage resp = t.Result;                            resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());                            return resp;                        });                    }                }                else                {                    return base.SendAsync(request, cancellationToken);                }            }        }

使用:在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盤點

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.