Learning ASP.NET Web API [Packt] – ASP.NET Core RC1 to ASP.NET Core 1.0

Hello All,

Recently, I published a video course on ASP.NET Web API using ASP.NET Core framework. Initially, when I started working on it, it was named as ASP.NET 5 and as it progressed till last section, Microsoft announced to rename it as ASP.NET Core and RC2 got released few days prior to the course release date. Microsoft took more than six months to release the next RC version. Although the concept was same but there were major changes in tooling and libraries. As it was not the final version so we decided to provide the details of differences once RTM releases.

In this post, I will be putting the details of the changes by section and also update the sample which will be available with the course. As ASP.NET 5 got renamed to ASP.NET Core, accordingly the names of libraries got changed to ASP.NET Core as well so we need to change all the references. The following table contains the details of packages that we need to update in our sample with the video number.

ASP.NET 5 Reference (Earlier) ASP.NET Core 1.0 Reference (Current) Video#
Microsoft.AspNet.Mvc Microsoft.ASPNETCore.MVC 2.2
EntityFramework.Core
EntityFramework.MicrosoftSqlServer
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
2.3
Microsoft.AspNet.Mvc.Formatters.Xml Microsoft.AspNetCore.Mvc.Formatters.Xml 2.4
Microsoft.AspNet.Mvc.TagHelpers
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNetCore.Mvc.TagHelpers
Microsoft.AspNetCore.Identity.EntityFrameworkCore
5.4

Updated sample is available with the course and refer the project.json to find the updated references. Also, Microsoft again reintroduced web.config file but it will be there along with Project.json.

Note – The details will be included for only for those those sections where changes are required.

Section 2   
As this was the first section where we started our discussion on ASP.NET Core Web API and started working on our sample so this section got many changes. Let’s discuss each

Video 2.1 : There are changes in the project creation flow. Earlier when we used to create ASP.NET Core project, it used to have two sets of references – one for core and other for full framework. We either used to build the application using both the framework and remove one based on our needs. As there were many libraries which could not work in both the platforms so Microsoft has provided the option to select the framework upfront while creating the project which makes the complete process simpler. Also, in real world scenarios, there are rare chances when we need to build the binaries for both the framework.  Now when we open New Project window and select web from left side then we get three options as
2.1Here we have three options.

  1. First one is a traditional ASP.NET application using .NET 4.6.
  2. Selected one is ASP.NET Core application using .NET Core framework and the same is used in our course.
  3. Third one is again ASP.NET Core application but uses the standard .NET framework.

When we select the second option, it shows the following dialog

2.1_2

It also got revamped completely. We had earlier lots of options which included standard ASP.NET templates. Now it contains only ASP.NET Core templates and has three options same as earlier ASP.NET 5 templates and we used the empty template for our course. Just to mention again, now we have just one bag named as .NETCoreApp,Version=v1.0  which contains set of libraries for .NET Core only in the references.

There are some more changes as below

a) Earlier we used to have following line in startup.cs which was entry point for the web application

// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);

but now we have a new file program.cs which contains the main method which is now entry point for the web application.

b) Configuration file web.config is also back in project file and available along with project.json although all the settings should be put in project.json and we will be using the same.

c) There are also changes in the number of the parameters in ConfigureServices method in startup.cs which includes Hosting Environment and logger factory but we will not be using it in our sample.

Video 2.2: Only change in the references. Refer the initial table.

Video 2.3: In this video, we discussed that there are four options to register a service but we found AddSingleton and AddInstance very similar, both allows single instance across multiple requests with a difference in the instance creation. Now we have only AddSingleton where either we can pass the instance or provide the type info as.

To register via interface and class name

services.AddSingleton<IBookStoreRepository, BookStoreRepository>();

and to register an instance

IBookStoreRepository bookStoreRepository = new BookStoreRepository(new BookStoreContext());
services.AddSingleton(bookStoreRepository);

Video 2.4: Only change in the references. Refer the table.

Section 3
In this section we added CRUD operations to our sample using  HTTP verbs. Only few changes are required in the section as mentioned below.

Video 3.2: Microsoft did an awesome change with it by making the JSON response in camel case by default. In our sample we added serialize settings in statrtup.cs as

options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

It is no more required.

Video 3.3 :  We returned various status codes from the action methods based on the request.The classes that we used also got renamed as

ASP.NET 5 ASP.NET Core 1.0
HttpUnauthorized Unauthorized
HttpNotFound (and its overloads) NotFound
HttpBadRequest (and its overloads) BadRequest

The above changes has taken place in all the action methods wherever used.

Section 4 
In this section, we added few more features to our sample like sorting, paging etc. Here there is a change in the way we access URL Helper as discussed below.

Video 4.3: We used URL helper for generating the URLs and it was injected via constructor without any other changes as it was by default available which is not the case now.

Now we need to access it via UrlHelperFactory and action context. ActionContext is accessed via ActionContextAccessor, for that we need to register it in startup.cs as

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

and we need to inject the UrlHelperFactory and ActionContextAccessor in constructor to get the URL helper as

  public BooksController(IBookStoreRepository _repository, IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionContextAccessor)
        {
            this.repository = _repository;
            this.urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
        }

Rest of the code would be same as we got the similar URL helper.

Section 5
In this section we talked about security implementation. In it we have only few changes as below.

Video 5.2 : We created a custom authorization attribute RequireHttpsAttribute which inherited from AuthorizationFilterAttribute where we checked the scheme from the URL. Now RequireHttpsAttribute is itself available under the namespace Microsoft.AspNetCore.Mvc so we can use the same to enforce the SSL in complete application or any specific controller/action.

Video 5.4 : Only few references changes. Refer the table

Section 6 
In this section, we discussed some advanced topics like DI, CORS etc and there are few changes in DI. Let’s see that

Video 6.1:
a) As discussed earlier that now we don’t have AddInstance option for registering the service, same can be achieved via AddSingleton.

b) We discussed that we can also inject services via property using FromServices attribute but it is not available any more as it was creating confusion and issues. Constructor injection is always preferable. From services is available and can be used for Action Injection as

public IEnumerable<Book> Get([FromServices] IBookStoreRepository repository)
{
...
}

These are the key changes that took place specific to Web API and our course. I created again the sample from scratch using the ASP.NET Core 1.0 which can be downloaded from the course.

Thanks a lot for your support and feedback.

Cheers
Brij

My Video Course : Learning ASP.NET Web API

Hello All,

9781785885945I am very happy to announce that my video course  Learning ASP.NET Web API using ASP.NET Core 1.0 got published. This course is for all the ASP.NET Developers who have little or no experience to Web API as it starts from basics and covers all the key aspects of Rest-ful services with real world examples. It will be similarly helpful to experienced Web API devs because developing it using ASP.NET Core is completely different and many old concepts cannot be used as it is.

The vision of the course is that the viewers understand that how to develop a RESTful web API using the ASP.NET Web API service, and be able to implement a service with a range of data transfer and handling operations. They will understand RESTful service architectures and how different types of application data can be exposed with a web API, to different client endpoints.Let me give overview of the course.

The key features of the course are

  • Develop a complete enterprise level REST based HTTP services from scratch using ASP.NET Core Web API with latest standards.
  • An example driven course from starting from basics of REST with brief description of new ASP.NET framework ASP.NET Core.
  •  Discusses all the building blocks: Routing, Controllers, Content Negotiations and security with advance topics like versioning, dependency Injection, caching etc.
  • Includes the tips and best practices for making robust and scalable APIs.
  • Full of pictorial presentations for core concepts, practical examples and clear step by step instructions with tips and best practices.

What you will learn from this course.

  • Understand REST basics and its constraints with real life examples.
  • ASP.NET Core framework changes and its impact of ASP.NET Web API.
  • Building blocks of ASP.NET Web API : Routing Controllers, HTTP verbs with scenario bases example.
  • Implement various data transfer operation and Content negotiation.
  • Various security implementations options including OAuth, CORS.
  • A good hand holding of Advance topics like dependency Injection, API versioning, HTTP Caching etc.
  • Consuming Web API end points using a real world client.
  • Tips and best practices of writing better, highly scalable and performant Web API service.

To find more about the video course and watch the sample video Click here.

Thanks a lot to all of you for your continuous support and feedback. Thanks a lot to Packt publishing for providing me the opportunity for this course and being supportive throughout the journey. Thanks a lot to my friends specially Arun for his time, support, feedback and reviews. Also I cannot forget to thanks my wife Renu for being so supportive and taking care of my son Anvit during my late night hours and weekends. Without their support it would not have been possible.

This book is based on my personal learning via blogs, samples, white papers, projects, POCs and many other sources. It has no relations with any of my current and previous employers. As this course is built on ASP.NET Core 1.0 which is not yet completely out and you may expect some changes in the final version. If you find any mistakes or have some constructive feedback, you can share it with me on my mail id – brij.mishra@outlook.com  I will try my best to address that at earliest.

Again, thanks a lot to all of you for your support and feedback. I am sure you will find it useful and will be very happy to see your valuable feedback and comments.

Cheers,
Brij

Unspecified Error while installing ASP.NET 5 RC1 Update 1 : Solution

Hello All,

Recently I installed Visual Studio update 1 on few new azure VMs but when I started installing ASP.NET 5 RC1 Update 1, I got the below error.

error

I tried to find the details on internet but not much information regrading this information. I saw some people find another Hash problem with this package but after looking it closely I found it different. Later when I looked into the log, I found the below details

Log files shows that it is not able to download DotNetVersionManager_x64 from https://go.microsoft.com/fwlink/?LinkId=708515. However, when I try from browser, it is downloading the msi. The error looks in the log as
[1124:12AC][2015-12-20T19:10:08]w343: Prompt for source of package: DotNetVersionManager_x64, payload: DotNetVersionManager_x64, path: C:\Users\WinS12R2Brij\Desktop\DotNetVersionManager-x64_rc1.msi
[1124:12AC][2015-12-20T19:10:08]i338: Acquiring package: DotNetVersionManager_x64, payload: DotNetVersionManager_x64, download from:https://go.microsoft.com/fwlink/?LinkId=708515
[1124:12AC][2015-12-20T19:10:08]e000: Error 0x80072f08: Failed to send request to URL: https://go.microsoft.com/fwlink/?LinkId=708515, trying to process HTTP status code anyway.
[1124:12AC][2015-12-20T19:10:08]e000: Error 0x80072f76: Failed attempt to download URL: ‘https://go.microsoft.com/fwlink/?LinkId=708515‘ to: ‘C:\Users\WINS12~1\AppData\Local\Temp\2\{782d25e1-8377-4417-a491-3013700fe300}\DotNetVersionManager_x64’

The error shows that it is preparing to download some packages but failing to send the request to the URL and returning some crazy HTTP status code anyway . I checked quickly internet connectivity as soon as I saw this error but it was working fine and even I tried to download from the requested URL directly from browser and it was downloading the package correctly.

After spending some more time and doing here n there, I downloaded the packages from all the URLs where it was failing and installed directly on my machine. I had to install three packages in the same to all the machines where I was getting the issue. Then I installed the original package and it ran smoothly. You can find the URLs from the log by looking specific line where you have Error 0x80072f08: Failed to send request to URL .

Before wrapping up, let me tell you that I didn’t find this issue on one of my machines but got the same on rest four VMs and some were having Windows Server 2012 R2 and 2016 technical preview. Two were having SQL 2014 and VS 2013 installed before installing VS 2015 update 1 and the above 1. On the machine where It went smooth without any issue that was also having similar configuration but I was using it from long time. Just provided this information for completeness as all the environment were quite similar.

Cheers
Brij

 

ASP.NET 5 RC1 Web API always returns JSON – Why ?


Hello All,

Note – For this example, I am have used Visual Studio 2015 Update 1 for IDE and ASP.NET 5 RC1.

Recently I started working on an ASP.NET Web API application but I got stuck at one point for few hours. Let’s start from scratch and create the application first then we will see the behavior and various options. As I (most of us) like to start from clean slate so I created an empty ASP.NET application and followed the below stuff

  1. Added Microsoft.AspNet.Mvc as dependency in project.json.
  2. In ConfigureServices method of startup.cs, added services.AddMvc()
  3. In Configure method of startup.cs, added app.UseMvc();
  4. Added a Controllers folder in solution and added a controller class with name as PeopleController which inherits from Controller.
  5. Added the attribute route on the controller as
  6. Now we have done all the necessary set up and added a Controller for Web API. I have added a DataHelper class in Models folder (which I added) which returns a list of persons.

Now when I run that application and call the API using Fiddler as

request

I get the response in JSON format

response

Although we didn’t send any Accept header in request. It means now the default response format is JSON only. Now I added the Accept header as

acceptrequest

Then also the response was same as earlier.

As per earlier understanding that the returned content type should be as per the Accept header which is not the case when I did some research, I found that now by default only JSON formatter is included. Refer the below link for detailed discussion.

https://github.com/aspnet/Mvc/issues/1765

And this was implemented in beta 3 release and it says that to add the XML formatter, we need to include the package Microsoft.AspNet.Mvc.Xml but I got an error while including this package because the latest version available is beta5 and the version of MVC we are using is rc1. After spending few hours, I discovered that the package Microsoft.AspNet.Mvc.Xml is not the correct one now and there was no update in it since 30th Jun’15. Two new packages for formatting XML and JSON format got introduced as

  1. Microsoft.AspNet.Mvc.Formatters.Xml
  2. Microsoft.AspNet.Mvc.Formatters.Json

Currently there is no details available on earlier package  that now some new packages are available instead of Microsoft.AspNet.Mvc.Xml  which made it bit tough to find the right one.

As we realized, JSON is included by default with MVC package, I added Xml package and configureed it in services as

public void ConfigureServices(IServiceCollection services)
{
    var mvcBuilder = services.AddMvc();
    mvcBuilder.AddXmlDataContractSerializerFormatters();
}

Now when I ran the package with Accept header as text/xml, it return the response in XML format as

xmlresponse

But default is JSON only so we don’t need to send any information in header if we just want the result in JSON format.

Cheers
Brij

 

A Great unification of Controllers: ASP.NET 5

This is another post on one of the cool features of ASP.NET 5. Microsoft introduced One ASP.NET concept with ASP.NET 4.5 which allows us to use MVC, Web API, Web forms in one project without any pain. But as we know that MVC and Web API follow the same coding constructs like controller, action but inherently they were different. There were some features like OutputCache (Refer one of my earlier post ) is available only with MVC not with Web API. Microsoft has redesigned ASP.NET MVC and Web API framework and made it truly one ASP.NET with vNext (ASP.NET 5). Now we can use the same controller to expose as an web-api endpoint and for returning the MVC views as well. As these are using the same framework now, all the features available with MVC can be seamlessly used with web api as well and vice versa.  Let’s have a pictorial look

Earlier versions of ASP.NET

All the MVC controllers are derived from Controller class under the name space System.Web.Mvc.

ControllersEarlier Continue reading

Your Dependency Injection ready ASP.NET : ASP.NET 5


Dependency Injection has become one the key design patterns of the current projects. It helps in writing loosely coupled code which makes the code easily testable and maintainable. As per wiki

Dependency injection is a software design pattern that implements inversion of control for software libraries. Caller delegates to an external framework the control flow of discovering and importing a service or software module specified or “injected” by the caller.

In this post, we will see that how easily we can implement this pattern with ASP.NET 5 projects and leverage various available options .

ASP.NET 5 got completely redesigned and made DI friendly. It provides a by default container which can be used while writing the application. It also enables us to use third party containers with it and you may need a adapter to use with ASP.NET. Continue reading

Presenting on ASP.NET 5 in #GIDS2015

GIDS_Website_LogoThe Great Indian Developer Summit (GIDS) is the largest and most popular annual conferences of India. This year it is taking place during April 21-24, 2015. I am very excited to share that I will be presenting there on ASPNET5 which was always very near to me . This version is bit different from earlier releases due to the massive changes that are taking place with it in this version. All the slides and the demos will be shared at the end of session. The details of of Talk are as below

BrijB1

Building Modern Web Applications with ASP.NET 5

ASP.NET 5 is now redesigned to cater to the needs of modern web applications. With the redesign, you can now  use the latest best practices such as dependency injection, TDD etc. ASP.NET 5 curtails many modules and components that we normally don’t use in our projects and hence boosts application speed. In this session we will examine the design shift that took place within ASP.NET 5 and how it resolves several of the problems that we encounter in our coding lives. At the end of session, you will have a good idea on the changes that ASP.NET5 brings to you as a developer.

If you are visiting this time, I will highly recommend to join this session for an hour and explore the awesomeness of ASP.NET 5. This session will be driven by demos with lots of Interactions

I am very excited to see you all there.

Cheers,
Brij

What is View component: ASP.NET 5

This is the second post on ASP.NET 5. In this post, we are going to explore one another very useful feature of ASP.NET 5. The link of my earlier post on ASP.NET 5 is

 Getting started with Tag Helpers – ASP.NET 5

ASP.NET 5 comes with another version of ASP.NET MVC that is ASP.NET MVC6.View Component is another very powerful got added with MVC 6. If you have not already gone through with this feature, you might just keep guessing about it and may correlate with multiple things. But this feature when you go through, you will enjoy it.

Before discussing this, How many of used Child Actions or know about that?

If you have used that you must have find it bit nasty. Child Actions are like a normal action but it can not be called by directly from url instead it is called from a view. The key usage of Child Action, when we want to reuse some part of UI at multiple places then we create a child action and use it at multiple places. One of the key issues was that with this, it makes another request to the server to call the action method, by going through the whole life cycle which makes the application slow. Also It can not be invoked asynchronously. Continue reading

Getting started with Tag Helpers – ASP.NET 5

ASP.NET has been always near and dear to me and it got more exciting for me as ASP.NET5 got revolutionary changes comparing to previous versions. All the changes has been done considering key points that are driving the software evolution like Agility, embracing latest design standards and technologies. It provides more capabilities, more power to developer, follows latest standards and helps in writing Cloud and mobile ready applications. As we know ASP.NET is like a umbrella of technologies and consists of ASP.NET MVC, ASP.NET WebForms, ASP.NET web api etc. All these technologies got lots of change and design to serves the modern web apps. ASP.NET5 comes with another new version of ASP.NET MVC6. I will be writing couple of posts on cool features of ASP.NET 5 that actually makes our life easy as a developer. Continue reading