Ejemplo n.º 1
0
        public ActionResult Task(HttpPostedFileBase fileUpload, HttpPostAttribute selboton)
        {
            if (fileUpload == null)
            {
                return(View(GetImageCollection()));
            }

            var cloudinary = new Cloudinary(
                new Account(
                    "raisky",
                    "712813241936831",
                    "Z9cprR-2l0R51ehGj5PIsUr2d3I"));

            var uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(fileUpload.FileName, fileUpload.InputStream),
            };

            var uploadResult = cloudinary.Upload(uploadParams);

            var uplPath = uploadResult.Uri;

            Image uploadedImage = new Image();

            uploadedImage.Path     = uplPath.AbsoluteUri;
            uploadedImage.User     = User.Identity.Name;
            uploadedImage.PublicId = uploadResult.PublicId;

            imageDataBase.Entry(uploadedImage).State = System.Data.Entity.EntityState.Added;
            imageDataBase.SaveChanges();

            return(View(GetImageCollection()));
        }
        public async Task BeforeRequestAsyncTest()
        {
            var context = new ApiActionContext
            {
                RequestMessage = new HttpApiRequestMessage
                {
                    RequestUri = new Uri("http://www.webapi.com/")
                },
                ApiActionDescriptor = ApiDescriptorCache.GetApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync"))
            };

            var attr = new HttpPostAttribute();
            await attr.BeforeRequestAsync(context);

            Assert.True(context.RequestMessage.Method == HttpMethod.Post);

            var attr2 = new HttpPostAttribute("/login");
            await attr2.BeforeRequestAsync(context);

            Assert.True(context.RequestMessage.Method == HttpMethod.Post);
            Assert.True(context.RequestMessage.RequestUri == new Uri("http://www.webapi.com/login"));

            var attr3 = new HttpPostAttribute("http://www.baidu.com");
            await attr3.BeforeRequestAsync(context);

            Assert.True(context.RequestMessage.Method == HttpMethod.Post);
            Assert.True(context.RequestMessage.RequestUri == new Uri("http://www.baidu.com"));
        }
        public async Task OnRequestAsyncTest()
        {
            var apiAction = new DefaultApiActionDescriptor(typeof(ITestApi).GetMethod("PostAsync"));
            var context   = new TestRequestContext(apiAction, string.Empty);

            context.HttpContext.RequestMessage.RequestUri = new Uri("http://www.webapi.com/");
            context.HttpContext.RequestMessage.Method     = HttpMethod.Post;


            var attr = new HttpPostAttribute();
            await attr.OnRequestAsync(context);

            Assert.True(context.HttpContext.RequestMessage.Method == HttpMethod.Post);

            var attr2 = new HttpPostAttribute("/login");
            await attr2.OnRequestAsync(context);

            Assert.True(context.HttpContext.RequestMessage.Method == HttpMethod.Post);
            Assert.True(context.HttpContext.RequestMessage.RequestUri == new Uri("http://www.webapi.com/login"));

            var attr3 = new HttpPostAttribute("http://www.baidu.com");
            await attr3.OnRequestAsync(context);

            Assert.True(context.HttpContext.RequestMessage.Method == HttpMethod.Post);
            Assert.True(context.HttpContext.RequestMessage.RequestUri == new Uri("http://www.baidu.com"));
        }
Ejemplo n.º 4
0
        public async Task BeforeRequestAsyncTest()
        {
            var context = new TestActionContext(
                httpApi: null,
                httpApiConfig: new HttpApiConfig(),
                apiActionDescriptor: new ApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync")));

            context.RequestMessage.RequestUri = new Uri("http://www.webapi.com/");
            context.RequestMessage.Method     = HttpMethod.Post;


            var attr = new HttpPostAttribute();
            await attr.BeforeRequestAsync(context);

            Assert.True(context.RequestMessage.Method == HttpMethod.Post);

            var attr2 = new HttpPostAttribute("/login");
            await attr2.BeforeRequestAsync(context);

            Assert.True(context.RequestMessage.Method == HttpMethod.Post);
            Assert.True(context.RequestMessage.RequestUri == new Uri("http://www.webapi.com/login"));

            var attr3 = new HttpPostAttribute("http://www.baidu.com");
            await attr3.BeforeRequestAsync(context);

            Assert.True(context.RequestMessage.Method == HttpMethod.Post);
            Assert.True(context.RequestMessage.RequestUri == new Uri("http://www.baidu.com"));
        }
Ejemplo n.º 5
0
        public ActionResult Login(HttpPostAttribute httpPost)
        {
            string username, password;

            username = Request.Form["username"];
            password = Request.Form["password"];


            // connect and verify username password
            return(RedirectToAction("Store"));
        }
Ejemplo n.º 6
0
        public DecryptMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            this.next = next;
            using TextReader reader = new StringReader(configuration.GetPivateKey());
            PemObject pemObject         = new PemReader(reader).ReadPemObject();
            AsymmetricKeyParameter pkey = PrivateKeyFactory.CreateKey(pemObject.Content);

            this.pkcs1Encoding = new Pkcs1Encoding(new RsaEngine());
            pkcs1Encoding.Init(false, pkey);
            var assembly = Assembly.GetExecutingAssembly();

            Type[] types          = assembly.GetTypes();
            Type[] apicontrollers = types.Where(type => type.GetCustomAttribute <ApiControllerAttribute>() != null).ToArray();
            foreach (Type ctrl in apicontrollers)
            {
                MethodInfo[]   controllerMethods = ctrl.GetMethods();
                RouteAttribute apiRoute          = ctrl.GetCustomAttribute <RouteAttribute>();
                if (apiRoute == null)
                {
                    throw new Exception($"{ctrl.Name} doesn't have a \"Route\" Attribute");
                }
                string ctrRoute = apiRoute.Template;
                foreach (MethodInfo meth in controllerMethods)
                {
                    EncryptAttribute encryptAttribute = meth.GetCustomAttribute <EncryptAttribute>();
                    if (encryptAttribute != null)
                    {
                        string            route;
                        HttpPostAttribute post = meth.GetCustomAttribute <HttpPostAttribute>();

                        if (post != null)
                        {
                            route = post.Template;
                        }
                        else
                        {
                            throw new Exception("Api Mehtod Be Encrypted Http Method Must Be POST ");
                        }
                        string key = "/" + ctrRoute + "/" + route;
                        if (this.ApiMap.ContainsKey(key))
                        {
                            throw new Exception("Api Method Route Repeat Exception!");
                        }

                        this.ApiMap.Add(key, encryptAttribute);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public ActionResult GetInfo(HttpPostAttribute post)
        {
            Console.WriteLine(Request.Params["id"]);
            int id = Convert.ToInt32(Request.Params["id"]);

            //var jsondata = employeeRepository.GetList().Where(e => e.BranchId == id);


            ArrayList list = new ArrayList();

            list.Add(employeeRepository.GetList().Where(e => e.BranchId == id));
            list.Add(servicesDirectoryRepository.GetAll());

            return(Json(list, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 8
0
        public static void AssertHttpPostOnly <T>(this T controller, Expression <Action <T> > action) where T : Controller
        {
            Type type = controller.GetType();
            MethodCallExpression body         = action.Body as MethodCallExpression;
            MethodInfo           actionMethod = body.Method;

            HttpPostAttribute postAttribute = actionMethod.GetCustomAttributes(typeof(HttpPostAttribute), false)
                                              .Cast <HttpPostAttribute>()
                                              .SingleOrDefault();

            HttpGetAttribute getAttribute = actionMethod.GetCustomAttributes(typeof(HttpGetAttribute), false)
                                            .Cast <HttpGetAttribute>()
                                            .SingleOrDefault();

            Assert.That(postAttribute != null && getAttribute == null,
                        "{0}.{1} does not have [HttpPost] attribute", controller.GetType().Name, actionMethod.Name);
        }
        /// <summary>
        /// Resolves any Mvc attributes on the method.
        /// </summary>
        /// <param name="methodBuilder">The method being built.</param>
        /// <param name="methodInfo">The method being called.</param>
        /// <returns>True if any resolved; otherwise false.</returns>
        public static bool ResolveMvcAttributes(
            this IMethodBuilder methodBuilder,
            MethodInfo methodInfo)
        {
            HttpGetAttribute getAttr = methodInfo.GetCustomAttribute <HttpGetAttribute>(true);

            if (getAttr != null)
            {
                methodBuilder.SetCustomAttribute(AttributeUtility.BuildAttribute <string, HttpGetAttribute>(getAttr.Template));
                return(true);
            }

            HttpPostAttribute postAttr = methodInfo.GetCustomAttribute <HttpPostAttribute>(true);

            if (postAttr != null)
            {
                methodBuilder.SetCustomAttribute(AttributeUtility.BuildAttribute <string, HttpPostAttribute>(postAttr.Template));
                return(true);
            }

            HttpPutAttribute putAttr = methodInfo.GetCustomAttribute <HttpPutAttribute>(true);

            if (putAttr != null)
            {
                methodBuilder.SetCustomAttribute(AttributeUtility.BuildAttribute <string, HttpPutAttribute>(putAttr.Template));
                return(true);
            }

            HttpPatchAttribute patchAttr = methodInfo.GetCustomAttribute <HttpPatchAttribute>(true);

            if (patchAttr != null)
            {
                methodBuilder.SetCustomAttribute(AttributeUtility.BuildAttribute <string, HttpPatchAttribute>(patchAttr.Template));
                return(true);
            }

            HttpDeleteAttribute deleteAttr = methodInfo.GetCustomAttribute <HttpDeleteAttribute>(true);

            if (deleteAttr != null)
            {
                methodBuilder.SetCustomAttribute(AttributeUtility.BuildAttribute <string, HttpDeleteAttribute>(deleteAttr.Template));
                return(true);
            }

            return(false);
        }
Ejemplo n.º 10
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var loginUser = AutofacExt.GetFromFac <LoginApp>().GetLoginUser();

            if (!User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }
            var controllername = Request.RequestContext.RouteData.Values["controller"].ToString().ToLower();
            var actionname     = filterContext.ActionDescriptor.ActionName.ToLower();

            var function = this.GetType().GetMethods().FirstOrDefault(u => u.Name.ToLower() == actionname);

            if (function == null)
            {
                throw new Exception("未能找到Action");
            }

            var anonymous = function.GetCustomAttribute(typeof(AnonymousAttribute));
            var module    = loginUser.Modules.FirstOrDefault(u => u.Url.ToLower().Contains(controllername));

            //当前登录用户没有Action记录&&Action没有anonymous标识
            if (module == null && anonymous == null)
            {
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }
            else
            {
                ViewBag.Module = module;  //为View显示服务,主要是为了显示按钮
            }

            var version = ConfigurationManager.AppSettings["version"];

            if (version == "demo")
            {
                HttpPostAttribute hobbyAttr = (HttpPostAttribute)Attribute.GetCustomAttribute(function, typeof(HttpPostAttribute));
                if (actionname.Contains("del") || hobbyAttr != null)  //客户端提交数据
                {
                    throw new HttpException(400, "演示版本,不能进行该操作,当前模块:" + controllername + "/" + actionname);
                }
            }

            base.OnActionExecuting(filterContext);
        }
Ejemplo n.º 11
0
        public void InitTest()
        {
            var descriptor = new ApiActionDescriptor("http://api.dev/", typeof(IAubTestApi).GetMethod("PostAsync"));

            var attr1 = new HttpPostAttribute();

            attr1.Init(descriptor);
            Assert.True(descriptor.Method == HttpMethod.Post);
            Assert.True(descriptor.Route == null);
            Assert.True(descriptor.Url == new Uri("http://api.dev"));

            var attr2 = new HttpPostAttribute("part-list");

            attr2.Init(descriptor);
            Assert.True(descriptor.Method == HttpMethod.Post);
            Assert.True(descriptor.Route == "part-list");
            Assert.True(descriptor.Url == new Uri("http://api.dev/part-list"));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Defines the request type of a controller method
        /// </summary>
        /// <param name="controllerName"></param>
        /// <param name="methodName"></param>
        /// <param name="methodAttributes"></param>
        /// <returns></returns>
        public static (RequestType, object) GetRequestType(string controllerName, string methodName, object[] methodAttributes)
        {
            try
            {
                var httpGetAttrCount    = methodAttributes.Count(x => x.GetType() == typeof(HttpGetAttribute));
                var httpPostAttrCount   = methodAttributes.Count(x => x.GetType() == typeof(HttpPostAttribute));
                var httpPutAttrCount    = methodAttributes.Count(x => x.GetType() == typeof(HttpPutAttribute));
                var httpDeleteAttrCount = methodAttributes.Count(x => x.GetType() == typeof(HttpDeleteAttribute));
                if ((httpGetAttrCount + httpPostAttrCount + httpPutAttrCount + httpDeleteAttrCount) > 1)
                {
                    throw new Exception($"Weber controller Error: Controller: {controllerName} => Method: {methodName} => Cannot have more than one request type attribute");
                }
                foreach (var attribute in methodAttributes)
                {
                    if (HttpGetAttribute.IsHttpGet(attribute))
                    {
                        return(RequestType.GET, attribute);
                    }

                    if (HttpPostAttribute.IsHttpPost(attribute))
                    {
                        return(RequestType.POST, attribute);
                    }

                    if (HttpPutAttribute.IsHttpPut(attribute))
                    {
                        return(RequestType.PUT, attribute);
                    }

                    if (HttpDeleteAttribute.IsHttpDelete(attribute))
                    {
                        return(RequestType.DELETE, attribute);
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception($"RequestTypeHelper GetRequestType Error: {e.Message}");
            }
            return(RequestType.None, null);
        }
        // GET: ProizvodModels/Edit/5
        public ActionResult Edit(int?id, HttpPostAttribute image1)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProizvodModel proizvodModel = db.proizvod.Find(id);

            if (proizvodModel == null)
            {
                return(HttpNotFound());
            }
            //  ViewBag.image1 = (from i in db.proizvod select i.Slika).Where(i => i.ProizvodiID.Equals(id));


            // var base64 = Convert.ToBase64String(proizvodModel.Slika);


            ViewBag.AutoID       = new SelectList(db.auto, "AutoID", "AutoNaziv", proizvodModel.AutoID);
            ViewBag.KategorijaID = new SelectList(db.kategorija, "KategorijaID", "KategorijaNaziv", proizvodModel.KategorijaID);
            return(View(proizvodModel));
        }
Ejemplo n.º 14
0
        List <SubscriptionInfo> GetEventSubscriptions()
        {
            List <SubscriptionInfo> eventSubscriptions = new List <SubscriptionInfo>();

            foreach (Type controllerType in ControllerTypes)
            {
                string callbackUrl = _DiscoveryMetadata.HostAddress;
                if (!callbackUrl.EndsWith("/"))
                {
                    callbackUrl += "/";
                }

                RouteAttribute routeAttr = controllerType.GetCustomAttribute <RouteAttribute>(false);
                if (routeAttr != null)
                {
                    callbackUrl += routeAttr.Template;
                    if (!callbackUrl.EndsWith("/"))
                    {
                        callbackUrl += "/";
                    }
                }

                MethodInfo[] methods = controllerType.GetMethods();
                foreach (MethodInfo methodInfo in methods)
                {
                    string route = string.Empty;

                    HttpPostAttribute httpPostAttr = methodInfo.GetCustomAttribute <HttpPostAttribute>();
                    if (httpPostAttr != null)
                    {
                        if (!string.IsNullOrWhiteSpace(httpPostAttr.Template))
                        {
                            route = httpPostAttr.Template;
                        }
                        else
                        {
                            routeAttr = methodInfo.GetCustomAttribute <RouteAttribute>();
                            if (routeAttr != null)
                            {
                                route = routeAttr.Template;
                            }
                        }

                        IEnumerable <SubscribeAttribute> subscribeAttrs = methodInfo.GetCustomAttributes <SubscribeAttribute>(true);
                        if (subscribeAttrs != null)
                        {
                            foreach (SubscribeAttribute subscribeAttribute in subscribeAttrs)
                            {
                                SubscriptionInfo subscriptionInfo = new SubscriptionInfo()
                                {
                                    HostName        = _HostName,
                                    Instance        = _Instance,
                                    CallbackAddress = callbackUrl + route,
                                    EventName       = subscribeAttribute.EventName
                                };

                                eventSubscriptions.Add(subscriptionInfo);
                            }
                        }
                    }
                    else
                    {
                        // subscription callback must be a POST
                    }
                }
            }

            return(eventSubscriptions);
        }
 public void LockUnlockHasHttpPostAttribute()
 {
     HttpPostAttribute attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute));
     Assert.NotNull(attr);
 }
 public void DeleteConfirmedHasHttpPostAttribute()
 {
     HttpPostAttribute attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.DeleteConfirmed), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute));
     Assert.NotNull(attr);
 }
 public void EditPostHasHttpPostAttribute()
 {
     HttpPostAttribute attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryModel), typeof(IFormFile) }).GetCustomAttribute(typeof(HttpPostAttribute));
     Assert.NotNull(attr);
 }
Ejemplo n.º 18
0
 public HttpPostWithValidForgeryToken()
 {
     _postAttribute        = new HttpPostAttribute();
     _antiForgeryAttribute = new ValidateAntiForgeryTokenAttribute();
 }
Ejemplo n.º 19
0
        public void Apply(ActionModel action)
        {
            var method = action.ActionMethod;

            if (method.IsDefined(typeof(HttpMethodAttribute)))
            {
                return;
            }
            action.Selectors.Clear();
            //custom prefix
            HttpMethodAttribute attr;

            foreach (var custom in _options.CustomRule)
            {
                if (action.ActionName.StartsWith(custom.Key))
                {
                    switch (custom.Value)
                    {
                    case HttpVerbs.HttpGet:
                        attr = new HttpGetAttribute(action.ActionName);
                        break;

                    case HttpVerbs.HttpPost:
                        attr = new HttpPostAttribute(action.ActionName);
                        break;

                    case HttpVerbs.HttpDelete:
                        attr = new HttpDeleteAttribute(action.ActionName);
                        break;

                    case HttpVerbs.HttpPut:
                        attr = new HttpPutAttribute(action.ActionName);
                        break;

                    default:
                        attr = new HttpPostAttribute(action.ActionName);
                        break;
                    }
                    ModelConventionHelper.AddRange(action.Selectors, ModelConventionHelper.CreateSelectors(new List <object> {
                        attr
                    }));
                    return;
                }
            }

            if (method.Name.StartsWith("Get"))
            {
                attr = new HttpGetAttribute(method.Name);
            }
            else if (method.Name.StartsWith("Post") || method.Name.StartsWith("Add"))
            {
                attr = new HttpPostAttribute(method.Name);
            }
            else if (method.Name.StartsWith("Update") || method.Name.StartsWith("Put"))
            {
                attr = new HttpPutAttribute(method.Name);
            }
            else if (method.Name.StartsWith("Del") || method.Name.StartsWith("Delete"))
            {
                attr = new HttpDeleteAttribute(method.Name);
            }
            else
            {
                attr = new HttpPostAttribute(method.Name);
            }
            ModelConventionHelper.AddRange(action.Selectors, ModelConventionHelper.CreateSelectors(new List <object> {
                attr
            }));
        }
Ejemplo n.º 20
0
        public async Task <ActionResult> GetController()
        {
            List <xQuyen> lstQuyens = new List <xQuyen>();

            Assembly asm = Assembly.GetExecutingAssembly();

            var q1 = asm
                     .GetExportedTypes()
                     .Where(x => typeof(CustomController).IsAssignableFrom(x) && !x.Name.Equals(typeof(CustomController).Name))
                     .Select(x => new
            {
                Controller = x.Name,
                Methods    = x.GetMethods().Where(y => y.DeclaringType.IsSubclassOf(typeof(CustomController)) && y.IsPublic && !y.IsStatic).ToList()
            });

            var BaseController = q1
                                 .Where(x => x.Controller.Equals(typeof(BaseController <>).Name))
                                 .Select(x => new
            {
                Controller = x.Controller.ToLower().Replace("controller", string.Empty),
                Actions    = x.Methods.Where(y => y.IsVirtual).Select(y => new { Action = y.Name.ToLower(), Attributes = y.GetCustomAttributes(false).ToList() })
            })
                                 .FirstOrDefault();

            var Controllers = q1
                              .Where(x => !x.Controller.Equals(typeof(BaseController <>).Name))
                              .Select(x => new
            {
                Controller = x.Controller.ToLower().Replace("controller", string.Empty),
                Actions    = x.Methods.Where(y => !y.IsVirtual).Select(y => new { Action = y.Name.ToLower(), Attributes = y.GetCustomAttributes(false).ToList() })
            });

            DateTime time = DateTime.Now;

            if (BaseController != null)
            {
                foreach (var action in BaseController.Actions)
                {
                    xQuyen quyen = new xQuyen();

                    HttpGetAttribute attr_Get   = (HttpGetAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpGetAttribute));
                    RouteAttribute   attr_Route = (RouteAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(RouteAttribute));
                    if (attr_Get != null && attr_Route != null)
                    {
                        quyen.Method   = HttpVerbs.Get.ToString().ToLower();
                        quyen.Template = string.IsNullOrWhiteSpace(attr_Route.Template) ? string.Empty : attr_Route.Template.ToLower();
                        lstQuyens.Add(quyen);
                    }
                    else if (attr_Get != null && attr_Route == null)
                    {
                        quyen.Method = HttpVerbs.Get.ToString().ToLower();
                        lstQuyens.Add(quyen);
                    }
                    else if (attr_Get == null && attr_Route != null)
                    {
                        quyen.Method   = HttpVerbs.Get.ToString().ToLower();
                        quyen.Template = string.IsNullOrWhiteSpace(attr_Route.Template) ? string.Empty : attr_Route.Template.ToLower();
                        lstQuyens.Add(quyen);
                    }

                    HttpPostAttribute attr_Post = (HttpPostAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpPostAttribute));
                    if (attr_Post != null)
                    {
                        quyen.Method = HttpVerbs.Post.ToString().ToLower();
                        lstQuyens.Add(quyen);
                    }

                    HttpPutAttribute attr_Put = (HttpPutAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpPutAttribute));
                    if (attr_Put != null)
                    {
                        quyen.Method = HttpVerbs.Put.ToString().ToLower();
                        lstQuyens.Add(quyen);
                    }

                    HttpDeleteAttribute attr_Delete = (HttpDeleteAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpDeleteAttribute));
                    if (attr_Delete != null)
                    {
                        quyen.Method = HttpVerbs.Delete.ToString().ToLower();
                        lstQuyens.Add(quyen);
                    }



                    quyen.KeyID      = 0;
                    quyen.NgayTao    = time;
                    quyen.Controller = BaseController.Controller;
                    quyen.Action     = action.Action;
                    quyen.MacDinh    = true;
                    quyen.Path       = string.Join("/", quyen.Controller, quyen.Action, quyen.Template).TrimEnd('/');
                }
            }

            foreach (var controller in Controllers)
            {
                List <xQuyen> lstTemps = new List <xQuyen>();

                foreach (var action in controller.Actions)
                {
                    xQuyen f = new xQuyen();

                    HttpGetAttribute attr_Get = (HttpGetAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpGetAttribute));
                    if (attr_Get != null)
                    {
                        f.Method = HttpVerbs.Get.ToString().ToLower();
                        // f.Template = string.IsNullOrWhiteSpace(attr_Get.Template) ? string.Empty : attr_Get.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    HttpPostAttribute attr_Post = (HttpPostAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpPostAttribute));
                    if (attr_Post != null)
                    {
                        f.Method = HttpVerbs.Post.ToString().ToLower();
                        //f.Template = string.IsNullOrWhiteSpace(attr_Post.Template) ? string.Empty : attr_Post.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    HttpPutAttribute attr_Put = (HttpPutAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpPutAttribute));
                    if (attr_Put != null)
                    {
                        f.Method = HttpVerbs.Put.ToString().ToLower();
                        // f.Template = string.IsNullOrWhiteSpace(attr_Put.Template) ? string.Empty : attr_Put.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    HttpDeleteAttribute attr_Delete = (HttpDeleteAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpDeleteAttribute));
                    if (attr_Delete != null)
                    {
                        f.Method = HttpVerbs.Delete.ToString().ToLower();
                        //  f.Template = string.IsNullOrWhiteSpace(attr_Delete.Template) ? string.Empty : attr_Delete.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    RouteAttribute attr_Route = (RouteAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(RouteAttribute));
                    if (attr_Route != null)
                    {
                        f.Method   = string.IsNullOrWhiteSpace(f.Method) ? HttpVerbs.Get.ToString().ToLower() : f.Method;
                        f.Template = string.IsNullOrWhiteSpace(attr_Route.Template) ? string.Empty : attr_Route.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    f.KeyID      = 0;
                    f.NgayTao    = time;
                    f.Controller = controller.Controller;
                    f.Action     = action.Action;
                    f.Path       = string.Join("/", f.Controller, f.Action, f.Template).TrimEnd('/');
                }

                lstQuyens.AddRange(lstTemps);
            }

            return(await SaveData(lstQuyens.ToArray()));
        }
Ejemplo n.º 21
0
        public async Task <IActionResult> GetController()
        {
            List <xFeature> lstFeatures = new List <xFeature>();

            Assembly asm = Assembly.GetExecutingAssembly();

            var Controllers = asm.GetExportedTypes()
                              .Where(x => typeof(ControllerBase).IsAssignableFrom(x) && !x.Name.Equals(typeof(BaseController <>).Name))
                              .Select(x => new
            {
                Controller = x.Name,
                Methods    = x.GetMethods().Where(y => y.DeclaringType.IsSubclassOf(typeof(ControllerBase)) && y.IsPublic && !y.IsStatic).ToList()
            })
                              .Select(x => new
            {
                Controller = x.Controller.ToLower().Replace("controller", string.Empty),
                Actions    = x.Methods.Select(y => new { Action = y.Name.ToLower(), Attributes = y.GetCustomAttributes(true).ToList() })
            });

            DateTime time = DateTime.Now;

            foreach (var controller in Controllers)
            {
                List <xFeature> lstTemps = new List <xFeature>();

                foreach (var action in controller.Actions)
                {
                    xFeature f = new xFeature();

                    HttpGetAttribute attr_Get = (HttpGetAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpGetAttribute));
                    if (attr_Get != null)
                    {
                        f.Method   = HttpMethods.Get.ToLower();
                        f.Template = string.IsNullOrWhiteSpace(attr_Get.Template) ? string.Empty : attr_Get.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    HttpPostAttribute attr_Post = (HttpPostAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpPostAttribute));
                    if (attr_Post != null)
                    {
                        f.Method   = HttpMethods.Post.ToLower();
                        f.Template = string.IsNullOrWhiteSpace(attr_Post.Template) ? string.Empty : attr_Post.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    HttpPutAttribute attr_Put = (HttpPutAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpPutAttribute));
                    if (attr_Put != null)
                    {
                        f.Method   = HttpMethods.Put.ToLower();
                        f.Template = string.IsNullOrWhiteSpace(attr_Put.Template) ? string.Empty : attr_Put.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    HttpDeleteAttribute attr_Delete = (HttpDeleteAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(HttpDeleteAttribute));
                    if (attr_Delete != null)
                    {
                        f.Method   = HttpMethods.Delete.ToLower();
                        f.Template = string.IsNullOrWhiteSpace(attr_Delete.Template) ? string.Empty : attr_Delete.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    RouteAttribute attr_Route = (RouteAttribute)action.Attributes.FirstOrDefault(x => x.GetType() == typeof(RouteAttribute));
                    if (attr_Route != null)
                    {
                        f.Method   = string.IsNullOrWhiteSpace(f.Method) ? HttpMethods.Get.ToLower() : f.Method;
                        f.Template = string.IsNullOrWhiteSpace(attr_Route.Template) ? string.Empty : attr_Route.Template.ToLower();
                        lstTemps.Add(f);
                    }

                    f.KeyID      = 0;
                    f.NgayTao    = time;
                    f.Controller = controller.Controller;
                    f.Action     = action.Action;
                    f.Path       = string.Join('/', "api", f.Controller, f.Template).TrimEnd('/');
                }

                lstFeatures.AddRange(lstTemps);
            }

            return(await SaveData(lstFeatures.ToArray()));
        }