码迷,mamicode.com
首页 > Windows程序 > 详细

ASP.NET API盘点

时间:2015-06-12 08:37:57      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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盘点

标签:

原文地址:http://www.cnblogs.com/GarsonZhang/p/4570766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!