We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with database using Entity Framework, resolving dependencies using Unity Container as well as using MEF. In all our sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers can use any Web API sample they have, else you can also use the sample applications we developed in my previous articles.
1) Single page applications (SPAs) use JavaScript to dynamically update the content of a single web page rather than loading entire new pages. This reduces page refreshes.
2) React is a popular JavaScript library for building user interfaces, especially for SPAs. It uses a virtual DOM for faster rendering.
3) Create-React-App is a command line interface that sets up a React project with common dependencies like Babel and Webpack preconfigured.
The document discusses JavaServer Faces (JSF), an MVC framework for building web interfaces. It provides:
- An overview of JSF concepts like managed beans, expression language, navigation rules, and components.
- Examples of using JSF for static and dynamic navigation between pages, including declaring beans and navigation rules in faces-config.xml.
- How JSF handles form submission and uses managed beans to represent request parameters and output data to results pages.
The document discusses Spring Boot, a framework for creating stand-alone, production-grade Spring based applications. It describes how Spring Boot allows creating projects quickly with features like embedded servers and auto-configuration. It then covers how to develop a basic Spring Boot web application including creating the project structure with Maven, adding controllers and properties files, and connecting to databases using Spring Data. Overall, the document provides an overview of Spring Boot and guidance on starting a Spring Boot web application project.
JSF 2 Notes with coding examples topics include introduction , managed bean, jsf tags, navigation, jsf life cycle and phase listners,jsf validation and converters, i18n
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
The Spring Framework provides a comprehensive Java platform for developing applications. It simplifies development by allowing developers to avoid dealing directly with complex APIs. Spring uses Inversion of Control and Dependency Injection to decouple classes and increase maintainability. The core Spring modules include beans, context, AOP, and aspects. Spring MVC implements the MVC pattern to build web applications, separating the model, view, and controller aspects.
1) Single page applications (SPAs) use JavaScript to dynamically update the content of a single web page rather than loading entire new pages. This reduces page refreshes.
2) React is a popular JavaScript library for building user interfaces, especially for SPAs. It uses a virtual DOM for faster rendering.
3) Create-React-App is a command line interface that sets up a React project with common dependencies like Babel and Webpack preconfigured.
The document discusses JavaServer Faces (JSF), an MVC framework for building web interfaces. It provides:
- An overview of JSF concepts like managed beans, expression language, navigation rules, and components.
- Examples of using JSF for static and dynamic navigation between pages, including declaring beans and navigation rules in faces-config.xml.
- How JSF handles form submission and uses managed beans to represent request parameters and output data to results pages.
The document discusses Spring Boot, a framework for creating stand-alone, production-grade Spring based applications. It describes how Spring Boot allows creating projects quickly with features like embedded servers and auto-configuration. It then covers how to develop a basic Spring Boot web application including creating the project structure with Maven, adding controllers and properties files, and connecting to databases using Spring Data. Overall, the document provides an overview of Spring Boot and guidance on starting a Spring Boot web application project.
JSF 2 Notes with coding examples topics include introduction , managed bean, jsf tags, navigation, jsf life cycle and phase listners,jsf validation and converters, i18n
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
The Spring Framework provides a comprehensive Java platform for developing applications. It simplifies development by allowing developers to avoid dealing directly with complex APIs. Spring uses Inversion of Control and Dependency Injection to decouple classes and increase maintainability. The core Spring modules include beans, context, AOP, and aspects. Spring MVC implements the MVC pattern to build web applications, separating the model, view, and controller aspects.
The document provides an overview of building server-side Java web applications using Tomcat, JSP, and JavaBeans, covering topics like installing Tomcat, creating Java and JSP projects, writing JSP pages and JavaBeans, using sessions and includes, and the Model 2 architecture. It includes tutorials on setting up a sample "Phones" application to demonstrate concepts like retrieving data from a database and displaying it dynamically in JSP pages.
This session will provide a complete tour of using the Spring MVC framework to build Java Portlets. It will include an in-depth review of a sample portlet application developed using the latest features of Spring MVC, including Annotation-based Controllers. If you are writing Portlets and using Spring, this session is for you.
We'll begin by discussing the unique differences and challenges when developing Portlets instead of traditional Servlet webapps. Then we'll talk about the unique approach that Spring MVC takes towards Portlets that fully leverages the Portlet lifecycle, instead of masking it like many other frameworks. We'll take an extensive tour of a sample application so we can see all the unique pieces of the framework in action. Finally we'll conclude with discussion of the upcoming support for the Portlet 2.0 (JSR 286) specification that will be part of Spring 3.0.
The document discusses three ways to handle errors in JSP:
1. Using Java exception handling mechanisms like try/catch blocks.
2. Specifying an error page using the errorPage attribute in the page directive.
3. Configuring error pages in the web deployment descriptor (web.xml) by mapping exceptions to error pages.
This document provides an overview of JavaServer Faces (JSF), including:
- An introduction to JSF and what it is
- A description of the JSF request lifecycle and faces servlet
- An explanation of JSF component models and commonly used tags
- A step-by-step guide for creating a basic "Hello World" JSF application
- Details about JSP architectures (Model 1 and Model 2) that provide context for JSF
Here are the 4 main ways to define routes in Symfony:
1. Annotations: Put routing information directly in controllers as annotations.
2. YAML configuration: Define routes in the routing.yml configuration file.
3. XML configuration: Define routes in the routing.xml configuration file.
4. PHP configuration: Define routes by creating and returning RouteCollection instances from routing.php files.
The YAML configuration method is most commonly used. It keeps routing separated from code and allows defining multiple routes in one centralized configuration file for better organization. Annotations can also be useful for simple applications. XML is not used much. And PHP configuration is only needed if routes need to be dynamically generated.
The document discusses request/response protocols for client-side scripts, server-side scripts, and Java Server Pages. It explains how a server can interface with multiple clients simultaneously using threads. An experiment is described to demonstrate refreshing a JSP page from multiple browsers. The effect of file extensions like .html vs .jsp is also examined.
Boston 2011 OTN Developer Days - Java EE 6Arun Gupta
The document provides an overview of new features in Java EE 6, including lightweight profiles, annotation-driven programming, and ease of development enhancements like packaging EJBs in WAR files. It lists the Java EE 6 specifications, major changes to specifications like JSF 2.0 and EJB 3.1, and new specifications like CDI 1.0.
JSF (JavaServer Faces) provides an event model, validation model, and conversion model to handle user input and events in web applications. The event model defines different event types like action, value change, and phase events that allow components to notify listeners of user interactions. The validation model validates user input on UI components using standard and custom validators. The conversion model converts between view data types like strings and model data types using standard and custom converters.
Java Server Pages (JSP) allow Java code to be embedded within HTML pages to create dynamic web content. JSP pages are translated into servlets by the web server. This involves compiling the JSP page into a Java servlet class that generates the HTML response. The servlet handles each request by executing the jspService() method and produces dynamic content which is returned to the client browser.
This document provides an introduction and overview of Struts, an MVC framework for Java web applications. It discusses Struts' main components and design patterns, including:
- Struts acts as an MVC framework, providing utilities for web app development using the MVC pattern.
- The framework has 3 main components - Controller, View, and Model.
- Struts uses the standard MVC design of separating data, presentation, and business logic into separate but interacting elements.
This document provides an introduction and overview of Ruby on Rails, including what it is, its key features and benefits, and how to get started building a basic web application with Rails. Some of the key points covered include Rails' emphasis on productivity through conventions over configuration, scaffolding, and its implementation of the MVC framework and full-stack capabilities. Examples are also given of generating a controller and view to output basic text and dynamic content.
Servers - Apache Tomcat Server
Server-side scripts - Java Server Pages
The document discusses request/response protocols for client-side scripts versus server-side scripts like Java Server Pages. It explains how a server can interact with multiple concurrent clients through multi-threaded responses. HTML meta-tags can control the request/response interaction, and the file extension (.html vs .jsp) affects how the page is processed.
This document provides an overview of Java Server Pages (JSP) technology. Some key points:
- JSP allows separation of work between web designers and developers by allowing HTML/CSS design and Java code to be placed in the same file.
- A JSP page is compiled into a servlet, so it can take advantage of servlet features like platform independence and database-driven applications.
- JSP pages use tags like <jsp:include> and <jsp:useBean> to include content and access JavaBeans. Scriptlets, expressions, declarations, and directives are also used.
- Implicit objects like request, response, out, and session are automatically available in JSP pages
JSF 2 and beyond: Keeping progress comingAndy Schwartz
Covers new features in JSF 2, community involvement in JSF and a look towards the future of this framework.
Presented by Dan Allen, Pete Muir and Andy Schwartz at Devoxx 2009.
http://www.devoxx.com/display/DV09/JSF+2+and+beyond
This seminar provides an introduction to Portlet development using the Spring MVC framework. Topics include: quick introductions to Spring and JSR 168 Portlets, setting up a Portlet development environment, an overview of the Spring MVC API, and then a series of sample applications that cover specific topics like Handler Mappings, Controllers, Interceptors, Form Controllers, File Uploads and the new Annotation-based Mappings introduced in Spring 2.5.
Sample code is available at:
http://www.ja-sig.org/wiki/x/CACDAQ
This document discusses migrating from JSF 1.1 to JSF 2.0. It highlights new features in JSF 2.0 including Facelets templating, Ajax support, and improved validation. When upgrading, issues may include custom components mixing technologies and JSP/JSF lifecycle conflicts. The document recommends converting JSPs to Facelets to avoid these issues, reusing existing components where possible, and using backing beans to remove logic from the view. Proper use of backing beans, custom tags, and initialization methods can help with code organization.
This document discusses unit testing Web APIs using the NUnit and Moq frameworks. It provides an overview of unit testing and the NUnit and Moq frameworks. It then details setting up a test project and installing necessary packages. The document focuses on writing unit tests for the business logic layer and controllers, demonstrating how to test a ProductService class by mocking dependencies, writing test methods, and more.
The document provides an overview of building server-side Java web applications using Tomcat, JSP, and JavaBeans, covering topics like installing Tomcat, creating Java and JSP projects, writing JSP pages and JavaBeans, using sessions and includes, and the Model 2 architecture. It includes tutorials on setting up a sample "Phones" application to demonstrate concepts like retrieving data from a database and displaying it dynamically in JSP pages.
This session will provide a complete tour of using the Spring MVC framework to build Java Portlets. It will include an in-depth review of a sample portlet application developed using the latest features of Spring MVC, including Annotation-based Controllers. If you are writing Portlets and using Spring, this session is for you.
We'll begin by discussing the unique differences and challenges when developing Portlets instead of traditional Servlet webapps. Then we'll talk about the unique approach that Spring MVC takes towards Portlets that fully leverages the Portlet lifecycle, instead of masking it like many other frameworks. We'll take an extensive tour of a sample application so we can see all the unique pieces of the framework in action. Finally we'll conclude with discussion of the upcoming support for the Portlet 2.0 (JSR 286) specification that will be part of Spring 3.0.
The document discusses three ways to handle errors in JSP:
1. Using Java exception handling mechanisms like try/catch blocks.
2. Specifying an error page using the errorPage attribute in the page directive.
3. Configuring error pages in the web deployment descriptor (web.xml) by mapping exceptions to error pages.
This document provides an overview of JavaServer Faces (JSF), including:
- An introduction to JSF and what it is
- A description of the JSF request lifecycle and faces servlet
- An explanation of JSF component models and commonly used tags
- A step-by-step guide for creating a basic "Hello World" JSF application
- Details about JSP architectures (Model 1 and Model 2) that provide context for JSF
Here are the 4 main ways to define routes in Symfony:
1. Annotations: Put routing information directly in controllers as annotations.
2. YAML configuration: Define routes in the routing.yml configuration file.
3. XML configuration: Define routes in the routing.xml configuration file.
4. PHP configuration: Define routes by creating and returning RouteCollection instances from routing.php files.
The YAML configuration method is most commonly used. It keeps routing separated from code and allows defining multiple routes in one centralized configuration file for better organization. Annotations can also be useful for simple applications. XML is not used much. And PHP configuration is only needed if routes need to be dynamically generated.
The document discusses request/response protocols for client-side scripts, server-side scripts, and Java Server Pages. It explains how a server can interface with multiple clients simultaneously using threads. An experiment is described to demonstrate refreshing a JSP page from multiple browsers. The effect of file extensions like .html vs .jsp is also examined.
Boston 2011 OTN Developer Days - Java EE 6Arun Gupta
The document provides an overview of new features in Java EE 6, including lightweight profiles, annotation-driven programming, and ease of development enhancements like packaging EJBs in WAR files. It lists the Java EE 6 specifications, major changes to specifications like JSF 2.0 and EJB 3.1, and new specifications like CDI 1.0.
JSF (JavaServer Faces) provides an event model, validation model, and conversion model to handle user input and events in web applications. The event model defines different event types like action, value change, and phase events that allow components to notify listeners of user interactions. The validation model validates user input on UI components using standard and custom validators. The conversion model converts between view data types like strings and model data types using standard and custom converters.
Java Server Pages (JSP) allow Java code to be embedded within HTML pages to create dynamic web content. JSP pages are translated into servlets by the web server. This involves compiling the JSP page into a Java servlet class that generates the HTML response. The servlet handles each request by executing the jspService() method and produces dynamic content which is returned to the client browser.
This document provides an introduction and overview of Struts, an MVC framework for Java web applications. It discusses Struts' main components and design patterns, including:
- Struts acts as an MVC framework, providing utilities for web app development using the MVC pattern.
- The framework has 3 main components - Controller, View, and Model.
- Struts uses the standard MVC design of separating data, presentation, and business logic into separate but interacting elements.
This document provides an introduction and overview of Ruby on Rails, including what it is, its key features and benefits, and how to get started building a basic web application with Rails. Some of the key points covered include Rails' emphasis on productivity through conventions over configuration, scaffolding, and its implementation of the MVC framework and full-stack capabilities. Examples are also given of generating a controller and view to output basic text and dynamic content.
Servers - Apache Tomcat Server
Server-side scripts - Java Server Pages
The document discusses request/response protocols for client-side scripts versus server-side scripts like Java Server Pages. It explains how a server can interact with multiple concurrent clients through multi-threaded responses. HTML meta-tags can control the request/response interaction, and the file extension (.html vs .jsp) affects how the page is processed.
This document provides an overview of Java Server Pages (JSP) technology. Some key points:
- JSP allows separation of work between web designers and developers by allowing HTML/CSS design and Java code to be placed in the same file.
- A JSP page is compiled into a servlet, so it can take advantage of servlet features like platform independence and database-driven applications.
- JSP pages use tags like <jsp:include> and <jsp:useBean> to include content and access JavaBeans. Scriptlets, expressions, declarations, and directives are also used.
- Implicit objects like request, response, out, and session are automatically available in JSP pages
JSF 2 and beyond: Keeping progress comingAndy Schwartz
Covers new features in JSF 2, community involvement in JSF and a look towards the future of this framework.
Presented by Dan Allen, Pete Muir and Andy Schwartz at Devoxx 2009.
http://www.devoxx.com/display/DV09/JSF+2+and+beyond
This seminar provides an introduction to Portlet development using the Spring MVC framework. Topics include: quick introductions to Spring and JSR 168 Portlets, setting up a Portlet development environment, an overview of the Spring MVC API, and then a series of sample applications that cover specific topics like Handler Mappings, Controllers, Interceptors, Form Controllers, File Uploads and the new Annotation-based Mappings introduced in Spring 2.5.
Sample code is available at:
http://www.ja-sig.org/wiki/x/CACDAQ
This document discusses migrating from JSF 1.1 to JSF 2.0. It highlights new features in JSF 2.0 including Facelets templating, Ajax support, and improved validation. When upgrading, issues may include custom components mixing technologies and JSP/JSF lifecycle conflicts. The document recommends converting JSPs to Facelets to avoid these issues, reusing existing components where possible, and using backing beans to remove logic from the view. Proper use of backing beans, custom tags, and initialization methods can help with code organization.
This document discusses unit testing Web APIs using the NUnit and Moq frameworks. It provides an overview of unit testing and the NUnit and Moq frameworks. It then details setting up a test project and installing necessary packages. The document focuses on writing unit tests for the business logic layer and controllers, demonstrating how to test a ProductService class by mocking dependencies, writing test methods, and more.
Resolve dependency of dependencies using Inversion of Control and dependency ...Akhil Mittal
In my last two articles I explained how to create a RESTful service using ASP.NET Web API working with Entity Framework and resolving dependencies using Unity Container. In this article I’ll explain how to create a loosely coupled system with Unity Container and MEF(Managed Extensibility Framework) using Inversion of Control. I’ll not be explaining much theory but rather focus more on practical implementations. For the readers who are following this series, they can use their existing solution that they have created till time. For my new readers of this article, I have provided the download link for the previous source code and current source code as well.
For theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC).
The document discusses implementing request and exception logging in ASP.NET Web APIs using NLog, Action Filters, and Exception Filters. It describes setting up NLog configuration, creating an NLogger class to handle logging, and adding an Action Filter (LoggingFilterAttribute) to log requests. It also covers adding an Exception Filter (GlobalExceptionAttribute) to log exceptions, modifying classes to support exception logging, and throwing an exception to test the exception logging.
This document discusses implementing security in a Web API using basic authentication and token-based authorization. It introduces basic authentication as a means of validating a user's credentials through a username and password sent in the request header. Token-based authorization is described as sending a token to authenticated users that allows them to access other resources. The document then outlines steps to create a user service, implement basic authentication using an authentication filter, and implement token-based authorization by setting up databases, services, and controllers and marking them with an authorization filter. Maintaining sessions with tokens is also briefly mentioned.
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
My article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learnt that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in a solution with a design flaw, we’ll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.
The document introduces ASP.NET Identity, which is Microsoft's new platform for managing users in ASP.NET applications. It has replaced the older ASP.NET Membership platform. The document discusses setting up an ASP.NET Identity implementation in an example project, including installing NuGet packages, defining a database context class, and creating a basic user management interface. It also provides an overview of how ASP.NET Identity uses OWIN/Katana to provide services to web applications in a more modular way compared to the previous ASP.NET Membership system.
The document provides an introduction and overview of ASP.NET MVC, covering topics such as routing, controllers, actions, views, and passing data between controllers and views. It compares ASP.NET MVC to traditional ASP.NET WebForms, outlines the MVC architecture and project structure, and describes how routing maps URLs to controller actions. Key aspects of controllers, views, partial views, HTML helpers, and view engines are also summarized.
The document discusses adding user management functionality to a Node.js application called QAVideos. It involves the following steps:
1. Creating the application using StrongLoop's Loopback framework.
2. Adding Angular support to handle data binding between the client and server.
3. Adding signup and login functionality including signup and success pages, a signup controller, and an authentication service to register new users.
Java spring mysql without hibernate(2) (1)AmedJacobReza
This document provides instructions for building a CRUD web application using Spring MVC, MySQL, and Mustache templates. It describes setting up the necessary technologies, creating controllers and views to handle requests and display data. Specifically, it outlines how to create controllers to handle GET and POST requests, retrieve and set model data, and render Mustache views. It also demonstrates using request parameters, path variables, arrays, lists, and form handling in Spring MVC.
Mvc interview questions – deep dive jinal desaijinaldesailive
Can you describe ASP.NET MVC Request Life Cycle? 1. Receive request, look up Route object in RouteTable collection and create RouteData object. 2. Create RequestContext instance. 3. Create MvcHandler and pass RequestContext to handler. 4. Identify IControllerFactory from RequestContext. 5. Create instance of class that implements ControllerBase. 6. Call MyController.Execute method. 7. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.
Java SpringBoot Book Build+Your+API+with+Spring.pdfmewajok782
This document discusses building a REST API with Spring and Java configuration. It covers setting up the Java configuration with @EnableWebMvc, testing the Spring context, creating a REST controller with request mappings and handling request/response bodies, mapping HTTP response codes, and additional dependencies needed for Spring Boot. The REST controller implements CRUD operations for a Foo resource by delegating requests to a service layer.
The document provides an overview of MVC 4.0 and various MVC concepts and techniques including:
- Unit testing in MVC using interfaces to create loosely coupled components and mocking frameworks.
- Exception handling in MVC using the OnException method and HandleError attribute to catch exceptions.
- Routing in MVC using the default route and custom routes added to the route table.
- Navigation structures in MVC using the MVC Site Map Provider which allows specifying controllers and actions in site maps.
- Styling MVC applications using layouts to define common templates applied to views.
- Implementing AJAX in MVC to update individual sections of a page without reloading using
The document describes setting up unit testing for a Web API project using NUnit and Moq frameworks. It includes:
1. Adding a test project and installing necessary packages like NUnit, Moq, EntityFramework, and Newtonsoft.Json.
2. Defining variables and setting up mocks for the repositories, services, and UnitOfWork classes needed for the tests.
3. Writing tests for the ProductController including getting all products, getting a product by ID, and testing exceptions.
4. Explaining how to mock the repositories to simulate database operations during the tests.
So in summary, it covers the steps to set up a Web API project for unit testing and then provides examples
This document discusses creating an MVC application from scratch using LINQ to SQL to perform CRUD operations on a database. It covers:
1. Creating an empty MVC project and adding controllers, views and models
2. Creating a sample database and using LINQ to SQL for communication between the MVC app and database
3. Performing CRUD operations in the MVC app by querying the database and passing data between controllers and views
ASP.NET MVC is a framework from Microsoft that separates an application's logic, presentation, and data access into three distinct components: models, views, and controllers. This separation of concerns makes the application easier to manage, test, and develop for large teams. ASP.NET MVC uses friendly URLs, does not rely on view state or server-based forms, and supports test-driven development better than traditional ASP.NET Web Forms applications.
The document provides an introduction to ASP.NET MVC, including:
- ASP.NET MVC helps reduce complexity by dividing an application into three layers: Model, View, and Controller. This separation of concerns improves maintainability and supports test-driven development.
- The Model layer represents core business logic and data. The View layer transforms models into visual representations. The Controller layer processes user input and coordinates between the view and model.
- Razor is a new view engine that uses a code-focused templating syntax to generate HTML in an expressive and fluid way within ASP.NET MVC applications.
- Entity Framework Code First allows defining data models as classes and using them with EF without explicit mapping,
The document outlines the key changes and new features in ASP.Net 4.0, including improvements to core services, Web Forms, and Visual Studio 2010 Web Designer. It discusses enhancements such as view state improvements, routing support, browser capabilities updates, and the addition of over 200 HTML and JScript code snippets. The presentation agenda and references provide additional resources for learning more about ASP.Net 4.0.
- ASP.NET MVC is a framework that enables building web applications using the Model-View-Controller pattern. It provides clear separation of concerns, testability, and fine-grained control over HTML and JavaScript.
- The key components of MVC are models (the data), views (the presentation), and controllers (which handle requests and respond by rendering a view). Controllers retrieve data from models and pass them to views to generate the response.
- ASP.NET MVC supports features like routing, dependency injection, and unit testing to build robust and maintainable web applications. It also maintains backward compatibility with existing ASP.NET technologies.
Meteor is a reactive web application framework that uses JavaScript on both the client and server. It provides reactivity through Tracker.autorun, which re-runs functions automatically when reactive data sources change. Meteor uses DDP for client-server communication and Minimongo, a MongoDB implementation, for client-side data caching. The document provides steps for creating a basic Meteor application with user accounts, routing, schemas, forms, and template helpers to display posts data reactively.
A developer has been working on an ASP.NET Core project for a few months. During that time he had various problems I had to fix. Then he converted his application to the RC2 version that was released a few weeks ago. Here we write down a post listing problems that could be fixed. Hope a few would find it useful.
This document provides an overview of the key concepts and architecture of Spring MVC, the model-view-controller framework in Spring. It discusses how Spring MVC handles requests and dispatches them to controller methods, and how controllers select views and expose model objects. It also covers view resolution, form processing, validation, exception handling, and REST support in Spring MVC, as well as its configuration options.
The document provides an introduction and overview of ASP.NET MVC, including a comparison to ASP.NET Web Forms. It discusses the model-view-controller pattern, routing, controllers, views and extensibility in ASP.NET MVC. The document also shares resources for learning more about ASP.NET MVC and provides an agenda for covering topics like testing and a real world walkthrough of an ASP.NET MVC application.
Similar to Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs (20)
This document discusses content negotiation in ASP.NET Web API 2. It explains what content negotiation is, why it is important, and how to implement it in Web API. Content negotiation allows a client to specify the desired response format using request headers like Accept and Content-Type. Web API uses formatters to serialize the response into the requested format. The document provides examples of configuring formatters to support different media types and customize the JSON output. It also describes how the content negotiation pipeline in Web API works to select the appropriate formatter based on the request headers.
The document discusses new and improved debugging features in Visual Studio 2015, including easier breakpoint configuration with an inline toolbar, simplified context menus, and settings windows that appear as peek windows. It also covers breakpoint conditions that allow hitting a breakpoint based on the number of hits or a conditional expression. Breakpoint actions allow logging messages to the output window. Additionally, the improved Error List in VS 2015 displays all errors at once, allows filtering by severity and error code, and links error codes to documentation.
This document discusses code refactoring techniques in Visual Studio 2015, including inline temporary variables and introducing local variables. It provides an example C# class with a method to fetch products above a certain price, and shows how Visual Studio's code refactoring suggestions can optimize the method in multiple steps. These include removing temporary variables, converting the method to an expression-bodied member, and reducing the code to a single line. The document emphasizes that code refactoring requires an understanding of how the changes will affect the code.
The document discusses renaming features in Visual Studio 2015. It describes how VS2015 provides renaming assistance through suggestions from the light bulb icon and previews changes before renaming. The renaming window allows renaming variables, methods, properties, classes, parameters and strings. It can also rename code comments and detect conflicts if the new name already exists. Renaming occurs inline and on the fly. The examples demonstrate renaming a variable, method, and parameter across multiple files. VS2015 helps optimize code through intelligent and automated renaming.
The document discusses Visual Studio's live static code analysis feature. It explains that this feature analyzes code in real-time as it is written, without requiring compilation, to detect errors and potential issues based on installed code analyzers. The document demonstrates how to install and use code analyzers through examples, showing how analyzers detect issues and provide suggestions to fix problems directly in the code editor through light bulb notifications. It provides a case study walking through fixing various issues detected in sample code using suggestions from an analyzer to iteratively improve the code quality.
The document discusses the code assistance features of Visual Studio 2015. It provides examples of how the light bulb icon displays potential fixes for syntax errors and missing code. It also shows how refactoring suggestions are provided to optimize code, such as removing unused namespaces or changing a method to directly return a value rather than using a temporary variable. The light bulb icon assists with code completion, error fixing, and refactoring to improve code quality and developer productivity.
Release planning is a challenging but important part of the agile development process. There are two main approaches to release planning: fixed timeline and fixed scope of work. With a fixed timeline, the deadline cannot be extended and functionality may need to be cut, while a fixed scope defines what must be included regardless of timeline. The objective of release planning is to baseline the product roadmap and team commitments, while allowing flexibility based on which approach is chosen.
This document discusses extending OData support in ASP.NET Web APIs. It provides an introduction to OData and the roadmap for a RESTful Web API series. It describes setting up a solution to add OData support and modifying existing API endpoints to be OData enabled. This allows queries to support options like $top, $filter, $orderby and more to filter, sort, page and select data from the server.
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
This document discusses implementing a generic repository pattern and unit of work pattern in an MVC application using Entity Framework. It begins by introducing the concepts of a generic repository and unit of work. It then shows how to create a generic repository class that can be used for any entity. A unit of work class is created to manage transactions and repositories. Properties on the unit of work class provide access to repositories without having to create separate classes. CRUD operations on entities are demonstrated using the generic repository through the unit of work. This completes the tutorial on implementing these patterns to reduce redundant code and complexity in an MVC application.
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
The document discusses implementing a repository pattern in an MVC application using Entity Framework. It begins with an introduction and roadmap of previous articles. It then discusses the benefits of a repository pattern in abstracting the data access layer from business logic. Steps are provided to create a sample repository interface and class to implement basic CRUD operations on a User entity, abstracting the data access code from the controller. The repository class uses the Entity Framework context to perform operations while resolving tight coupling issues between layers. It concludes that while this implementation works for a single entity, a generic repository will be needed to cleanly support multiple entities without duplication.
MVC Application using EntityFramework Code-First approach Part4Akhil Mittal
This document discusses connecting an MVC application to a database using Entity Framework's Code First approach. It explains that with Code First, domain models are designed first before the database is automatically generated. The steps shown create a DbContext class that inherits from DbContext and defines a DbSet for the User model. A connection string is added and the DbContext is used instead of the prior Entity Data Model classes. When run, the database is dynamically generated based on the model, allowing CRUD operations on the User table through the application and Entity Framework.
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
This document discusses connecting an existing MVC application to a database using Entity Framework instead of LINQ to SQL. It provides steps to generate an Entity Data Model from an existing database, generate strongly typed entity classes, and modify the application's controllers to use the Entity Framework context instead of the LINQ to SQL context. The key steps are: 1) Adding an Entity Data Model file and generating entity classes; 2) Modifying controllers to use the Entity Framework context instead of LINQ to SQL; 3) Binding views to the generated entity classes. The document emphasizes that Entity Framework automates CRUD operations and allows focusing on business logic rather than data access code.
This document introduces the MVC architecture and separation of concerns. It outlines a 6 part roadmap to cover MVC fundamentals and implementing it with Entity Framework. Part 1 introduces MVC, defining the roles of models, views, and controllers. It explains how MVC separates the application into independent and reusable components for the model, views for presentation, and controllers for handling requests. This separation aims to improve maintainability and extensibility of applications.
C sharp and asp.net interview questionsAkhil Mittal
The document provides summaries of common questions and answers related to ASP.NET, C#, and the .NET framework. It defines view state as storing the current property settings of an ASP.NET page and controls to detect form submissions. It explains that user controls allow reusing ASP.NET pages as controls, and validation controls perform input checking on server controls. The document also distinguishes between Response.Write and Response.Output.Write, and lists page life cycle methods like Init, Load, and Unload.
This document provides answers to common ASP.NET interview questions. It begins with questions about the differences between custom controls and user controls, ASP session state and ASP.NET session state, and datasets versus recordsets in ADO.NET. Subsequent questions cover topics like view state, authentication, caching, validation controls, and working with data controls.
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
I have been writing a lot about advanced topics like MVC, Entity Framework, Repository Patterns etc., my priority always remains to cover the topic as a whole, so that a reader do not have to search for missing links anywhere else. My this article will cover almost every OOPS concept that a novice/beginner developer hunt for, and not only beginners, the article’s purpose is to be helpful to experience professionals also who need to sometimes brush-up their concepts or who prepare for interviews .
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Akhil Mittal
My article of the series “Diving in OOP” will explain enum datatype in C#. We’ll learn by doing hands on lab and not only by theory. We’ll explore the power of enum and will cover almost every scenario in which we can use enum. We’ll follow a practical approach of learning to understand this concept. We may come across complex examples to understand the concept more deeply.
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Akhil Mittal
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Akhil Mittal
The document discusses runtime polymorphism in C# using method overriding. It shows how to override methods in a derived class by marking the base class methods as virtual and using the override keyword in the derived class. An experiment is conducted where calling a method on an object initialized as the base class but actually referring to a derived class instance results in the overridden method from the derived class being called due to runtime binding.
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Akhil Mittal
This document provides an overview of abstract classes in C# object-oriented programming. It defines abstract classes as classes that cannot be instantiated and must be implemented in derived classes. The document demonstrates several key features of abstract classes through code examples, including: defining abstract and non-abstract methods in abstract classes; inheriting from abstract classes to instantiate derived classes; and requiring derived classes to implement abstract methods from the base abstract class.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceIndexBug
Imagine a world where machines not only perform tasks but also learn, adapt, and make decisions. This is the promise of Artificial Intelligence (AI), a technology that's not just enhancing our lives but revolutionizing entire industries.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Essentials of Automations: The Art of Triggers and Actions in FME
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
1. RESTful Day #4:
Custom URL Re-Writing/Routing using
Attribute Routes in MVC 4 Web APIs
–by Akhil Mittal
Table of Contents
Table of Contents _________________________________________________________________________ 1
Introduction _____________________________________________________________________________ 1
Roadmap _______________________________________________________________________________ 2
Routing _________________________________________________________________________________ 2
Existing Design and Problem ________________________________________________________________ 3
Attribute Routing _________________________________________________________________________ 8
Setup REST endpoint / WebAPI project to define Routes_________________________________________ 10
More Routing Constraints _________________________________________________________________ 15
Range: _______________________________________________________________________________________15
Regular Expression:_____________________________________________________________________________16
Optional Parameters and Default Parameters: _______________________________________________________16
RoutePrefix: Routing at Controller level ______________________________________________________ 19
RoutePrefix: Versioning ___________________________________________________________________ 20
RoutePrefix: Overriding ___________________________________________________________________ 20
Disable Default Routes____________________________________________________________________ 21
Running the application___________________________________________________________________ 21
Conclusion______________________________________________________________________________ 26
References _____________________________________________________________________________ 26
Introduction
We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with
database using Entity Framework, resolving dependencies using Unity Container as well as using MEF.In all our
sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll
explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as
well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers
can use any Web API sample they have, else you can also use the sample applications we developed in my
previous articles.
2. Roadmap
Let’s revisit the road map that I started on Web API,
Here is my roadmap for learning RESTful APIs,
RESTful Day #1: Enterprise level application architecture with Web API’s using Entity Framework, Generic
Repository pattern and Unit of Work.
RESTful Day #2: Inversion of control using dependency injection in Web API's using Unity Container and
Bootstrapper.
RESTful Day #3: Resolve dependency of dependencies using Inversion of Control and dependency injection in
Asp.net Web APIs with Unity Container and Managed Extensibility Framework (MEF).
RESTful Day #4: Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs.
RESTful Day #5: Basic Authentication and Token based custom Authorization in Web API’s using Action Filters.
RESTful Day #6: Request logging and Exception handing/logging in Web API’s using Action Filters, Exception
Filters and nLog.
RESTful Day #7: Unit testing Asp.Net Web API's controllers using nUnit.
RESTful Day #8: Extending OData support in Asp.Net Web API's.
I’ll purposely use Visual Studio 2010 and .net Framework 4.0 because there are few implementations that are
very hard to find in .Net Framework 4.0, but I’ll make it easy by showing how we can do it.
Routing
3. Image credit : http://www.victig.com/wp-content/uploads/2010/12/routing.jpg
Routing in generic terms for any service, api, website is a kind of pattern defining system that tries to
maps all request from the clients and resolves that request by providing some response to that request.In
WebAPI we can define routes in WebAPIConfig file, these routes are defined in an internal Route Table.We
can define multiple sets of Routes in that table.
Existing Design and Problem
We already have an existing design. If you open the solution, you’ll get to see the structure as mentioned
below,
4. In our existing application, we created WebAPI with default routes as mentioned in the file named
WebApiConfig in App_Start folder of WebApi project.The routes were mentioned in the Register method as,
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Do not get confused by MVC routes, since we are using MVC project we also get MVC routes defined in
RouteConfig.cs file as,
5. public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
We need to focus on the first one i.e. WebAPI route. As you can see in the following image, what each
property signifies,
We have a route name, we have a common URL pattern for all routes, and option to provide optional
parameters as well.
Since our application do not have particular different action names, and we were using HTTP VERBS as action
names, we didn’t bother much about routes.Our Action names were like ,
1. public HttpResponseMessage Get()
2. public HttpResponseMessage Get(int id)
3. public int Post([FromBody] ProductEntity productEntity)
4. public bool Put(int id, [FromBody]ProductEntity productEntity)
5. public bool Delete(int id)
Default route defined does not takes HTTP VERBS action names into consideration and treat them default
actions, therefore it does not mentions {action} in routeTemplate. But that’s not limitation, we can have our
own routes defined in WebApiConfig , for example, check out the following routes,
6. public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionBased",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionBased",
routeTemplate: "api/{controller}/action/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
And etc. In above mentioned routes, we can have action names as well, if we have custom actions.
So there is no limit to define routes in WebAPI. But there are few limitations to this, note we are talking about
WebAPI 1 that we use with .Net Framework 4.0 in Visual Studio 2010.Web API 2 has overcome those
limitations by including the solution that I’ll explain in this article. Let’s check out the limitations of these
routes,
7. Yes, these are the limitations that I am talking about in Web API 1.
If we have route template like routeTemplate: "api/{controller}/{id}" or routeTemplate:
"api/{controller}/{action}/{id}" or routeTemplate: "api/{controller}/action/{action}/{id}",
We can never have custom routes and will have to slick to old route convention provided by MVC.Suppose
your client of the project wants to expose multiple endpoints for the service, he can’t do so.We also can not
have our own defined names for the routes, so lots of limitation.
Let’s suppose we want to have following kind of routes for my web api endpoints,where I can define versions
too,
v1/Products/Product/allproducts
v1/Products/Product/productid/1
v1/Products/Product/particularproduct/4
v1/Products/Product/myproduct/<with a range>
v1/Products/Product/create
v1/Products/Product/update/3
and so on, then we cannot achieve this with existing model.
Fortunately these things have been taken care of in WebAPI 2 with MVC 5 , but for this situation we have
AttributeRouting to resolve and overcome these limitations.
8. Attribute Routing
Attribute Routing is all about creating custom routes at controller level, action level.We can have multiple
routes using Attribute Routing. We can have versions of routes as well, in short we have the solution for our
exiting problems. Let’s straight away jump on how we can implement this in our exising project.I am not
explaining on how to create a WebAPI, for that you can refer my first post of the series.
Step 1: Open the solution ,and open Package Manage Console like shown below in the figure,
Goto Tools->Library Packet manage-> Packet Manager Console
Step 2: In the package manager console window at left corner of Visual Studio type, Install-Package
AttributeRouting.WebApi, and choose the project WebApi or your own API project if you are using any other
code sample, then press enter.
9. Step 3: As soon as the package is installed, you’ll get a class named AttributeRoutingHttpConfig.cs in your
App_Start folder.
This class has its own method to RegisterRoutes, which internally maps attribute routes.It has a start method
that picks Routes defined from GlobalConfiguration and calls the RegisterRoutes method,
using System.Web.Http;
using AttributeRouting.Web.Http.WebHost;
[assembly: WebActivator.PreApplicationStartMethod(typeof(WebApi.AttributeRoutingHttpConfig),
"Start")]
namespace WebApi
{
public static class AttributeRoutingHttpConfig
{
public static void RegisterRoutes(HttpRouteCollection routes)
{
// See http://github.com/mccalltd/AttributeRouting/wiki for more options.
10. // To debug routes locally using the built in ASP.NET development server,
go to /routes.axd
routes.MapHttpAttributeRoutes();
}
public static void Start()
{
RegisterRoutes(GlobalConfiguration.Configuration.Routes);
}
}
}
We don’t even have to touch this class, our custom routes will automatically be taken care of using this
class.We just need to focus on defining routes. No coding . You can now use route specific stuff like route
names, verbs,constraints,optional parameters,default parameters,methods,route areas,area mappings,route
prefixes,route conventions etc.
Setup REST endpoint / WebAPI project to define Routes
Our 90% of the job is done.
We now need to setup or WebAPI project and define our routes.
Our existing ProductController class looks something like shown below,
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BusinessEntities;
using BusinessServices;
namespace WebApi.Controllers
{
public class ProductController : ApiController
{
private readonly IProductServices _productServices;
11. #region Public Constructor
/// <summary>
/// Public constructor to initialize product service instance
/// </summary>
public ProductController(IProductServices productServices)
{
_productServices = productServices;
}
#endregion
// GET api/product
public HttpResponseMessage Get()
{
var products = _productServices.GetAllProducts();
var productEntities = products as List<ProductEntity> ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not
found");
}
// GET api/product/5
public HttpResponseMessage Get(int id)
{
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for
this id");
}
// POST api/product
public int Post([FromBody] ProductEntity productEntity)
{
return _productServices.CreateProduct(productEntity);
}
// PUT api/product/5
public bool Put(int id, [FromBody] ProductEntity productEntity)
{
if (id > 0)
{
return _productServices.UpdateProduct(id, productEntity);
}
return false;
}
// DELETE api/product/5
public bool Delete(int id)
{
if (id > 0)
return _productServices.DeleteProduct(id);
return false;
12. }
}
}
Where we have a controller name Product and Action names as Verbs. When we run the application, we get
following type of endpoints only(please ignore port and localhost setting. It’s because I run this application
from my local environment),
Get All Products:
http://localhost:40784/api/Product
Get product By Id:
http://localhost:40784/api/Product/3
Create product :
http://localhost:40784/api/Product (with json body)
Update product:
http://localhost:40784/api/Product/3 (with json body)
Delete product:
http://localhost:40784/api/Product/3
Step 1: Add two namespaces to your controller,
using AttributeRouting;
using AttributeRouting.Web.Http;
Step 2: Decorate your action with different routes,
13. Like in above image, I defined a route with name productid which taked id as a parameter.We also have to
provide verb (GET,POST,PUT,DELETE,PATCH) along with the route like shown in image. So it is
[GET(“productid/{id?}”)]. You can define whatever route you want for your Action like
[GET(“product/id/{id?}”)], [GET(“myproduct/id/{id?}”)] and many more.
Now when I run the application and navigate to /help page, I get this,
14. i.e. I got one more route for Getting product by id.When you’ll test this service you’ll get your desired url
something like : http://localhost:55959/Product/productid/3, that sounds like real REST .
Similarly decorate your Action with multiple routes like show below,
// GET api/product/5
[GET("productid/{id?}")]
[GET("particularproduct/{id?}")]
[GET("myproduct/{id:range(1, 3)}")]
public HttpResponseMessage Get(int id)
{
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for
this id");
}
15. Therefore we see, we can have our custom route names and as well as multiple endpoints for a single
Action.That’s exciting.Each endpoint will be different but will serve same set of result.
{id?} : here ‘?’ means that parameter can be optional.
[GET("myproduct/{id:range(1, 3)}")], signifies that the product id’s falling in this range
will only be shown.
More Routing Constraints
You can leverage numerous Routing Constraints provided by Attribute Routing.I am taking example of some of
them,
Range:
To get the product within range, we can define the value, on condition that it should exist in database.
[GET("myproduct/{id:range(1, 3)}")]
16. public HttpResponseMessage Get(int id)
{
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for
this id");
}
Regular Expression:
You can use it well for text/string parameters more efficiently.
[GET(@"id/{e:regex(^[0-9]$)}")]
public HttpResponseMessage Get(int id)
{
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for
this id");
}
e.g. [GET(@"text/{e:regex(^[A-Z][a-z][0-9]$)}")]
Optional Parameters and Default Parameters:
You can also mark the service parameters as optional in the route. For example you want to fetch an employee detail
from the data base with his name,
[GET("employee/name/{firstname}/{lastname?}")]
public string GetEmployeeName(string firstname, string lastname=”mittal”)
{
…………….
……………….
}
In the above mentioned code, I marked last name as optional by using question mark ‘?’ to fetch the employee detail.
It’s my end user wish to provide the last name or not.
So the above endpoint could be accessed through GET verb with urls,
~/employee/name/akhil/mittal
~/employee/name/akhil
If a route parameter defined is marked optional, you must also provide a default value for that method
parameter.
In the above example, I marked ‘lastname’ as an optional one and so provided a default value in the
method parameter , if user doesn’t send any value, “mittal” will be used.
In .Net 4.5 Visual Studio > 2010 with WebAPI 2, you can define DefaultRoute as an attribute too, just try
it by your own.Use attribute [DefaultRoute] to define default route values.
17. You can try giving custom routes to all your controller actions.
I marked my actions as,
// GET api/product
[GET("allproducts")]
[GET("all")]
public HttpResponseMessage Get()
{
var products = _productServices.GetAllProducts();
var productEntities = products as List<ProductEntity> ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not
found");
}
// GET api/product/5
[GET("productid/{id?}")]
[GET("particularproduct/{id?}")]
[GET("myproduct/{id:range(1, 3)}")]
public HttpResponseMessage Get(int id)
{
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for
this id");
}
// POST api/product
[POST("Create")]
[POST("Register")]
public int Post([FromBody] ProductEntity productEntity)
{
return _productServices.CreateProduct(productEntity);
}
// PUT api/product/5
[PUT("Update/productid/{id}")]
[PUT("Modify/productid/{id}")]
public bool Put(int id, [FromBody] ProductEntity productEntity)
{
if (id > 0)
{
return _productServices.UpdateProduct(id, productEntity);
}
return false;
}
// DELETE api/product/5
[DELETE("remove/productid/{id}")]
[DELETE("clear/productid/{id}")]
[PUT("delete/productid/{id}")]
18. public bool Delete(int id)
{
if (id > 0)
return _productServices.DeleteProduct(id);
return false;
}
And therefore get the routes as,
GET:
POST / PUT / DELETE:
19. Check for more constraints here.
You must be seeing “v1/Products” in every route, that is due to RoutePrefix I have used at controller level.Let’s discuss
RoutePrefix in detail.
RoutePrefix: Routing at Controller level
We were marking our actions with particular route, but guess what , we can mark our controllers too with certain route
names, we can achieve this by using RoutePrefix attribute of AttributeRouting.Our controller was named Product, and I
want to append Products/Product before my every action, there fore without duplicating the code at each and every
action, I can decorate my Controller class with this name like shown below,
[RoutePrefix("Products/Product")]
public class ProductController : ApiController
{
Now, since our controller is marked with this route, it will append the same to every action too.For e.g. route of
following action,
[GET("allproducts")]
[GET("all")]
public HttpResponseMessage Get()
20. {
var products = _productServices.GetAllProducts();
var productEntities = products as List<ProductEntity> ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not
found");
}
Now becomes,
~/Products/Product/allproducts
~/Products/Product/all
RoutePrefix: Versioning
Route prefix can also be used for versioning of the endpoints, like in my code I provided “v1” as version in my
RoutePrefix as shown below,
[RoutePrefix("v1/Products/Product")]
public class ProductController : ApiController
{
Therefore “v1” will be appended to every route / endpoint of the service. When we release next version, we can
certainly maintain a change log separately and mark the endpoint as “v2” at controller level, that will append “v2” to all
actions,
e.g.
~/v1/Products/Product/allproducts
~/v1/Products/Product/all
~/v2/Products/Product/allproducts
~/v2/Products/Product/all
RoutePrefix: Overriding
This functionality is present in .Net 4.5 with Visual Studio > 2010 with WebAPI 2.You can test it there.
There could be situations that we do not want to use RoutePrefix for each and every action.AttributeRouting provides
such flexibility too, that despite of RoutePrefix present at controller level, an individual action could have its own route
too.It just need to override the default route like shown below,
RoutePrefix at Controller :
[RoutePrefix("v1/Products/Product")]
public class ProductController : ApiController
{
Independent Route of Action:
[Route("~/MyRoute/allproducts")]
public HttpResponseMessage Get()
21. {
var products = _productServices.GetAllProducts();
var productEntities = products as List<ProductEntity> ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not
found");
}
Disable Default Routes
You must be wondering that in the list of all the URL’s on service help page, we are getting some different/other routes
that we have not defined through attribute routing starting like ~/api/Product. These routes are the outcome of default
route provided in WebApiConfig file, remember??. If you want to get rid of those unwanted routes, just go and
comment everything written in Register method in WebApiConfig.cs file under Appi_Start folder,
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
You can also remove the complete Register method, but for that you need to remove its calling too from Global.asax file.
Running the application
Just run the application, we get,
We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right
clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
22. You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas->
HelpPage like shown below,
I have already provided the database scripts and data in my previous article, you can use the same.
Append “/help” in the application url, and you’ll get the test client,
GET:
24. You can test each service by clicking on it. Once you click on the service link, you'll be redirected to test the
service page of that particular service. On that page there is a button Test API in the right bottom corner, just
press that button to test your service,
Service for Get All products,
25. Likewise you can test all the service endpoints.
Image source: http://www.rsc.org/eic/sites/default/files/upload/cwtype-Endpoint.jpg and
http://www.guybutlerphotography.com/EEGDemoConstruction/wp-content/uploads/2013/01/asthma-
endpoint_shutterstock_89266522_small.jpg
26. Conclusion
We now know how to define our custom endpoints and what its benefits are. Just to share that this library
was introduced by Tim Call, author of http://attributerouting.net and Microsoft has included this in WebAPI
2 by default.My next article will explain token based authentication using ActionFilters in WepAPI. Till then
Happy Coding you can also download the complete source code from GitHub. Add the required packages, if
they are missing in the source code.
Click Github Repository to browse for complete source code.
References
http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
https://github.com/mccalltd/AttributeRouting
About Author
Akhil Mittal works as a Sr. Analyst in Magic Software and have an experience of more than 8 years in C#.Net. He is a
codeproject and a c-sharpcorner MVP (Most Valuable Professional). Akhil is a B.Tech (Bachelor of Technology) in
Computer Science and holds a diploma in Information Security and Application Development from CDAC. His work
experience includes Development of Enterprise Applications using C#, .Net and Sql Server, Analysis as well as Research
and Development. His expertise is in web application development. He is a MCP (Microsoft Certified Professional) in
Web Applications (MCTS-70-528, MCTS-70-515) and .Net Framework 2.0 (MCTS-70-536).