ASP.Net Flashcards

1
Q

Describe Areas

A

Areas provide a way to separate a large MVC application into semantically-related groups of models, views, and controllers.

Project name

  • Areas
    • Products
      • Controllers
        • HomeController.cs
      • Views
        • Home
          • Index.cshtml
    • Services
      • Controllers
        • HomeController.cs
      • Views
        • Home
        • Index.cshtml
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is OWIN?

A

OWIN stands for Open Web Interface for .NET. OWIN is a specification that defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is OpenAPI?

A

OpenAPI Specification (formerly Swagger Specification) is an API description format for REST APIs. An OpenAPI file allows you to describe your entire API, including:

Available endpoints (/users) and operations on each endpoint (GET /users, POST /users)
Operation parameters Input and output for each operation
Authentication methods
Contact information, license, terms of use and other information.

API specifications can be written in YAML or JSON. The format is easy to learn and readable to both humans and machines. The complete OpenAPI Specification can be found on GitHub: OpenAPI 3.0 Specification

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What Is Swagger?

A

Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document and consume REST APIs. The major Swagger tools include:

Swagger Editor – browser-based editor where you can write OpenAPI specs.
Swagger UI – renders OpenAPI specs as interactive API documentation.
Swagger Codegen – generates server stubs and client libraries from an OpenAPI spec.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Describe the Server layer in the Katana Architecture

A

REFERENCE: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/an-overview-of-project-katana

The host is responsible for:

  • Managing the underlying process.
  • Orchestrating the workflow that results in the selection of a server and the construction of an OWIN pipeline through which requests will be handled.

At present, there are 3 primary hosting options for Katana-based applications:

IIS/ASP.NET: Using the standard HttpModule and HttpHandler types, OWIN pipelines can run on IIS as a part of an ASP.NET request flow. ASP.NET hosting support is enabled by installing the Microsoft.AspNet.Host.SystemWeb NuGet package into a Web application project. Additionally, because IIS acts as both a host and a server, the OWIN server/host distinction is conflated in this NuGet package, meaning that if using the SystemWeb host, a developer cannot substitute an alternate server implementation.

Custom Host: The Katana component suite gives a developer the ability to host applications in her own custom process, whether that is a console application, Windows service, etc. This capability looks similar to the self-host capability provided by Web API. The following example shows a custom host of Web API code:

OwinHost.exe: While some will want to write a custom process to run Katana Web applications, many would prefer to simply launch a pre-built executable that can start a server and run their application. For this scenario, the Katana component suite includes OwinHost.exe. When run from within a project’s root directory, this executable will start a server (it uses the HttpListener server by default) and use conventions to find and run the user’s startup class. For more granular control, the executable provides a number of additional command line parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Describe the Server layer in the Katana Architecture

A

REFERENCE: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/an-overview-of-project-katana

While the host is responsible for starting and maintaining process within which the application runs, the responsibility of the server is to open a network socket, listen for requests, and send them through the pipeline of OWIN components specified by the user. Currently, the Katana project includes two server implementations:

Microsoft.Owin.Host.SystemWeb: As previously mentioned, IIS in concert with the ASP.NET pipeline acts as both a host and a server. Therefore, when choosing this hosting option, IIS both manages host-level concerns such as process activation and listens for HTTP requests. For ASP.NET Web applications, it then sends the requests into the ASP.NET pipeline. The Katana SystemWeb host registers an ASP.NET HttpModule and HttpHandler to intercept requests as they flow through the HTTP pipeline and send them through the user-specified OWIN pipeline.

Microsoft.Owin.Host.HttpListener: As its name indicates, this Katana server uses the .NET Framework’s HttpListener class to open a socket and send requests into a developer-specified OWIN pipeline. This is currently the default server selection for both the Katana self-host API and OwinHost.exe.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Describe the Middleware/framework layer of the Katana Architecture

A

REFERENCE: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/an-overview-of-project-katana

When the server accepts a request from a client, it is responsible for passing it through a pipeline of OWIN components, which are specified by the developer’s startup code. These pipeline components are known as middleware.
At a very basic level, an OWIN middleware component simply needs to implement the OWIN application delegate so that it is callable.

Func, Task>

Katana supports a handful of conventions and helper types for middleware components. The most common of these is the OwinMiddleware class. A custom middleware component built using this class would look similar to the following:

public class LoggerMiddleware : OwinMiddleware
{
    private readonly ILog _logger;
    public LoggerMiddleware(OwinMiddleware next, ILog logger) : base(next)
    {
        _logger = logger;
    }
public override async Task Invoke(IOwinContext context)
{
    _logger.LogInfo("Middleware begin");
    await this.Next.Invoke(context);
    _logger.LogInfo("Middleware end");
} }

Middleware components are added to the pipeline in the Startup class. The Katana infrastructure will build the pipeline of middleware components based on the order in which they were added to the IAppBuilder object in the Configuration method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Describe the Application layer of the Katana Architecture

A

REFERENCE: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/an-overview-of-project-katana

The application layer will continue to use the ASP.Net framework irrespective of whether or not the application runs in an OWIN pipeline using components from the Katana project. The one place where OWIN-related code will be visible to the application developer will be the application startup code, where the developer composes the OWIN pipeline. In the startup code, the developer will register a series of UseXx statements, generally one for each middleware component that will process incoming requests. Typically, a larger framework middleware, such as ASP.NET Web API or SignalR will be registered at the end of the pipeline. Cross-cutting middleware components, such as those for authentication or caching, are generally registered towards the beginning of the pipeline so that they will process requests for all of the frameworks and components registered later in the pipeline. This separation of the middleware components from each other and from the underlying infrastructure components enables the components to evolve at different velocities while ensuring that the overall system remains stable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Exception Handling - Using HttpResponseException

A

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

For example, the following method of EmployeeController returns Status code 404 (not found), if employee data is not found for ID.
public Employee Get([FromODataUri] int key)  
{  
    Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
    if (data == null)  
    {  
        throw new HttpResponseException(HttpStatusCode.NotFound);  
    }  
    return data;  
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Exception Handling - Using HttpError

A

CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client. CreateErrorResponse creates an instance of HttpError object and returns it as HttpResponseMessage object.
public HttpResponseMessage Get([FromODataUri] int key)
{
Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();
if (data == null)
{
string message = string.Format(“No Employee found with ID = {0}”, key);
returnRequest.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
returnRequest.CreateResponse(HttpStatusCode.OK, data);;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Exception Handling - Using Exception Filters

A

Exception filters can be used to handle unhandled exceptions which are generated in Web API. The exception filter can be able to catch the unhandled exceptions in Web API. This filter is executed when an action method throws the unhandled exception. Note that exception filter does not catch HttpResponseException exception because HttpResponseException is specifically designed to return the HTTP response.

We can use exception filter whenever controller action method throws an unhandled exception that is not an HttpResponseException. This is an attribute so we can decorate both action method and controller with this. Exception filter is very similar to HandleErrorAttribute in MVC.

The code shown below helps to implement the custom exception filter.
namespace WebAPITest  
{  
    using System.Net;  
    usingSystem.Net.Http;  
    usingSystem.Web.Http.Filters;  
    public class CustomExceptionFilter: ExceptionFilterAttribute  
    {  
        public override void OnException(HttpActionExecutedContextactionExecutedContext)  
        {  
            string exceptionMessage = string.Empty;  
            if (actionExecutedContext.Exception.InnerException == null)  
            {  
                exceptionMessage = actionExecutedContext.Exception.Message;  
            }  
            else  
            {  
                exceptionMessage = actionExecutedContext.Exception.InnerException.Message;  
            }  
            //We can log this exception message to the file or database.  
            var response = newHttpResponseMessage(HttpStatusCode.InternalServerError)  
            {  
                Content = newStringContent(“An unhandled exception was thrown by service.”),  
                    ReasonPhrase = "Internal Server Error.Please Contact your Administrator."  
            };  
            actionExecutedContext.Response = response;  
        }  
    }  
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Exception Handling - Using Exception Handlers

A
Normally, exception filter is used to catch the unhandled exception. This approach will work fine but it fails if any error is raised from outside action. For example, if any error is raised in the following area then exception filter will not work.
Error inside the exception filter.
Exception related to routing.
Error inside the Message Handlers class.
Error in Controller Constructor.

Web API 2 provides a good alternative way to achieve global exception handling. Web API provides “ExceptionHandler” abstract class to handle exception above said area.

Using the following code, we can define the custom implementation of ExceptionHandler.
namespace WebAPITest
{
using System.Net;
usingSystem.Net.Http;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingSystem.Web.Http.ExceptionHandling;
usingSystem.Web.Http.Results;
publicclassGlobalExceptionHandler: ExceptionHandler
{
public async override TaskHandleAsync(ExceptionHandlerContext context, CancellationTokencancellationToken)
{
// Access Exception using context.Exception;
conststringerrorMessage = “An unexpected error occured”;
var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new
{
Message = errorMessage
});
response.Headers.Add(“X-Error”, errorMessage);
context.Result = newResponseMessageResult(response);
}
}
}
Same as exception filter, Exception handler is also required to be registered. ExceptionHandler is inheriting from IExceptionHandler interface and Web API has already this type of class registered so we just need to replace this class to our custom exception handler class because Web API doesn’t support multiple ExceptionHandler.
public static class WebApiConfig
{
public static void Register(HttpConfigurationconfig)
{
config.Filters.Add(new CustomExceptionFilter());
config.Services.Replace(typeof(IExceptionHandler), newGlobalExceptionHandler());
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly