ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 Hosting - ASPHostPortal.com :: Page Instrumentation in ASP.NET 4.5

clock December 27, 2013 11:03 by author Robert

 

In this article, I showed you how to use Page Instrumentation, a new  feature in ASP.NET 4.5 which might be useful for you during debugging.
ASP.NET 4.5 include a hidden gem called Page Instrumentation, very few people aware of this gem. You can use page instrumentation in ASP.NET 4.5 WebForm and MVC 5 or 4(assuming it targets 4.5). It allows you to inspect/instrument a web form or a mvc view during the rendering process. Page instrumentation are useful in scenarios when you have some performance issues regarding view engine rendering. In this article, I will show you how to use this feature in ASP.NET 4.5.

To start instrumenting a page, you need to inherit PageExecutionListener class.

The BeginContext will be called by a view engine before it renders the output for the specified context. Similarly, EndContext called by a view engine after it renders the output for the specified context. Both of these methods accept PageExecutionContext class as a parameter which have the following members.

All the properties of PageExecutionContext class are self explanatory. Let assume we have the following MVC view(for understanding how many times and when the BeginContext and EndContext will be invoke by the framework).

The Razor View Engine will emit the following C# code


Finally, here is a simple implementation of PageExecutionListener class which calculates the total time each time whenever something is written to the output response.

 



ASP.NET Hosting with ASPHostPortal.com :: Working With ASP.Net Web Forms in Visual Studio 2013

clock December 23, 2013 11:56 by author Ben

Here you will create the data models and use the entity classes in it. The Entity Framework is used as a reference to use the entity classes. The Entity Framework is an Object Relational Mapping (ORM) framework. We use it to reduce the data access code that we used to access the data. It provides the entity classes to access the data using LINQ.

 

There are various types of approaches in Entity Framework. We'll use the Code First Approach to define the data models by using classes. We'll map them to an existing database or use it to generate the new database. The Entity Framework reference already exists in the references in the ASP.NET Web Forms Application. You can see that in the screenshot below:

If it is not present then it can be installed from the NuGet Package Manager. You must have a reference to the System.Data.Entity namespace to include the Entity Framework. It enables the classes to query, insert, update and delete the data. To install the Entity namespace, use the following procedure:

Step 1: Right-click on "References" and click on "Add Reference".

We'll create the class to specify the schema of the data and such a class is called an Entity Class. We'll create properties here to designate the fields in our table in the database. Use the following procedure to create the classes.

Step 1: In your Solution Explorer, right-click on the "Models" folder to add a class.

Step 2: Enter the name of the class as "Cricketer".

 

Step 3: Replace the class code with the code given below:

Add the following assembly:

using System.ComponentModel.DataAnnotations;

Code:

public class Cricketer

{

    [ScaffoldColumn(false)]

    public int CricketerID { get; set; }

  

    [Required, StringLength(100), Display (Name="Name")]

    public string CricketerName { get; set; }

  

    [Required, StringLength(50)]

    public string Team { get; set; }

 

    [Required]

    public string Grade { get; set; }

    public int? DetailsID { get; set; }

    public virtual Detail Detail { get; set; }

}

Step 4: Generate another class named Detail.

Add the following assembly:

using System.ComponentModel.DataAnnotations;

Then replace the class code with the following code:

public class Detail

{

    [ScaffoldColumn(false)]

    public int DetailsID { get; set; }

 

    [Required]

    public int ODI { get; set; }

 

    [Required]

    public int Test { get; set; }

    public virtual ICollection<Cricketer> Cricketers { get; set; }

}

Data Annotations

As you'd see above, some of the properties have the attributes designating the restrictions about the member such as [ScaffoldColumn(false)]. These are called data annotations. They specify the details and describe the validations for the user.

Context Class

We need to define the context class to use the classes for data accessing from the table in the database. Use the following procedure to add a context class.

Step 1: Right-click on the "Models" folder to add a new class.

Step 2: Enter the class name as CricketerContext.

Step 3:

Add the following assembly:

using System.Data.Entity;

Then replace the code with the following code:

public class CricketerContext : DbContext

{

    public CricketerContext()

        : base("WebFormsApplication")

    {

    }

 

    public DbSet<Detail> Details { get; set; }

    public DbSet<Cricketer> Cricketers { get; set; }

}


The class defined above represents the Entity Framework cricketer database context and to handle the storing and updating of the Cricketer class instances in the database.

Database Initializer Class

We'll provide some custom logic to initialize the database for running the first time the context is to be used. This will allow adding the seeded data to the database that represents the cricketer and details data.

Step 1: Add another class named CricketerDatabaseInitializer in the models folder.

Step 2:

Add the following assembly:

using System.Data.Entity;

Then modify your code with the following code:

public class CricketerDatabaseInitializer : DropCreateDatabaseIfModelChanges<CricketerContext>

{

    protected override void Seed(CricketerContext context)

    {

        GetDetails().ForEach(d => context.Details.Add(d));

        GetCricketers().ForEach(c => context.Cricketers.Add(c));

    }

 

    private static List<Detail> GetDetails()

    {

        var details = new List<Detail> {

            new Detail

            {

                DetailsID = 1, ODI = 463, Test = 200

            },

            new Detail

            {

                DetailsID = 2, ODI = 311, Test = 113

            },

            new Detail

            {

                DetailsID = 3, ODI = 344, Test = 164

            },

            new Detail

            {

                DetailsID = 4, ODI = 375, Test = 168

            },

        };

 

        return details;

    }

 

    private static List<Cricketer> GetCricketers()

    {

        var cricketers = new List<Cricketer> {

            new Cricketer

            {

                CricketerID = 1, CricketerName = "yourname",

                Team = "India", Grade = "A", DetailsID = 1,

            },

            new Cricketer

            {

                CricketerID = 2, CricketerName = "Saurav Ganguly",

                Team = "India", Grade = "A", DetailsID = 2,

            },

            new Cricketer

            {

                CricketerID = 3, CricketerName = "
yourname",

                Team = "India", Grade = "A", DetailsID = 3,

            },

            new Cricketer

            {

                CricketerID = 4, CricketerName = "
yourname",

                Team = "Australia", Grade = "A", DetailsID = 4,

            },

    };

 

        return cricketers;

    }

}


The seed property is overridden and set after the initialization and creation of the database. The values from the details and cricketers display on the database. If we modify the database by changing the values through the code above, we'll not see the updated values after running the application because the code uses an implementation of the DropCreateDatabaseIfModelChanges class to recognize if the model has changed before resetting the seed data.

Now we have four classes that are created here. For example:

 

Application Configuration

Now, we need to configure the application to use the Model classes. There are two main sections given below:

    Global File Configuration

    Open the Global.asax file.

    Add the following assembly:

    using System.Data.Entity;

    using WebFormsApplication.Models;

    Then modify the code with the following code:

    void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

        RouteConfig.RegisterRoutes(RouteTable.Routes);

        BundleConfig.RegisterBundles(BundleTable.Bundles);

        Database.SetInitializer(new CricketerDatabaseInitializer());

    }
    


    Web Config File Configuration

    Open the Web.config file and add the following in the connection string:
    

    <add name="WebFormsApplication" connectionString="Data Source=(LocalDb)\v11.0;
         AttachDbFilename=|DataDirectory|\WebFormsApp.mdf;
         Integrated Security=True"

         providerName="System.Data.SqlClient" />



ASP.NET 4.0 Hosting - ASPHostPortal.com :: Initialize assemblies using PreApplicationStartMethod for ASP.NET 4.0 Application

clock December 20, 2013 05:44 by author Robert

Sometimes your ASP.NET application needs to hook up some code before even the Application is started. Assemblies supports a custom attribute called PreApplicationStartMethod which can be applied to any assembly that should be loaded to your ASP.NET application, and the ASP.NET engine will call the method you specify within it before actually running any of code defined in the application.

Lets discuss how to use it using Steps :

1. Add an assembly to an application and add this custom attribute to the AssemblyInfo.cs. Remember, the method you speicify for initialize should be public static void method without any argument. Lets define a method Initialize. You need to write :

[assembly:PreApplicationStartMethod(typeof(MyInitializer.InitializeType), "InitializeApp")]

2. After you define this to an assembly you need to add some code inside InitializeType.InitializeApp method within the assembly.

public static class InitializeType
{
    public static void InitializeApp()
    {
          // Initialize application
    }

}

3. You must reference this class library so that when the application starts and ASP.NET starts loading the dependent assemblies, it will call the method InitializeApp automatically.

Warning

Even though you can use this attribute easily, you should be aware that you can define these kind of method in all of your assemblies that you reference, but there is no guarantee in what order each of the method to be called. Hence it is recommended to define this method to be isolated and without side effect of other dependent assemblies.

The method InitializeApp will be called way before the Application_start event or even before the App_code is compiled.

This attribute is mainly used to write code for registering assemblies or build providers.

 



Enterprise Email Hosting :: ASPHostPortal.com Launches Reliable and Scalable Enterprise Email Hosting

clock December 17, 2013 05:04 by author Ben

ASPHostPortal.com, a leading Windows web hosting provider, proudly announces Enterprise Email Hosting for all costumer. With Enterprise Email Hosting Services from ASPHostPortal.com, you’ll find the perfect hosted email solution for your small business. These professional tools and features enable you to access and manage your email and communicate and collaborate from your desktop or mobile devices anywhere in the world.

Enterprise Email Hosting uses the Internet to communicate information about promotions, company offerings, product updates and more. It is a valuable dialogue between a prospective or current customer and a company. Enterprise Email Hosting is more cost effective, and achieves results faster than traditional direct mail marketing. Most importantly, This service is twice as effective as traditional direct mail in getting a response from the targeted audience.

ASPHostPortal.com offer Enterprise Email hosting with the following features:

  • 2 GB Mailbox Space
  • Support Blackberry
  • WebMail Access
  • POP/SMTP/IMAP
  • Total Bulk Email up to 10.000 emails/month


"An  enterprise email hosting account costs $8.00 per month and gives you 10 mailbox that you can access using your smartphone especially Blackberry, Webmail and POP3 Email programs like Outlook.  Once it is ordered it is available to use immediately."said Dean Thomas, Manager at ASPHostPortal.com.

Web hosting is gaining huge amount of popularity because of its several benefits. The most popular hosting of all is Email hosting. A good email hosting has the ability to protect all the important emails.

Where to look for the best email hosting service? How to know more about the different types of hosting services? Read more about it on http://www.asphostportal.com.


About ASPHostPortal.com:


ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



Free, Best and Reliable Entity Framework 6 Hosting with ASPHostPortal.com

clock December 11, 2013 05:21 by author William

Entity Framework is actively developed by the Entity Framework team which is assigned to the Microsoft Open Tech Hub and in collaboration with a community of open source developers. Together we are dedicated to creating the best possible data access experience for .NET developers.
The Entity Framework version 6 Release Candidate is now available to developers for immediate download. The open source object-relational mapper is designed to enable .NET developers to work with relational data using domain-specific objects. Entity Framework allows programmers to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database.

There are The Top features of Entity Framework 6 :

  • Connection Resiliency - enables automatic recovery from transient connection failures.
  • Async Query and Save - dds support for the task-based asynchronous patterns that were introduced in .NET 4.5. With .NET 4.5 Microsoft introduced async and await keywords but in EF 5 Microsoft didn't have time to add support for async query and save but now with EF6 it is supported.
  • Code-Based Configuration - gives you the option of performing configuration - that was traditionally performed in a config file - in code.
  • Dependency Resolution - introduces support for the Service Locator pattern and we’ve factored out some pieces of functionality that can be replaced with custom implementations.
  • Interception/SQL logging - provides low-level building blocks for interception of EF operations with simple SQL logging built on top.
  • Testability improvements - make it easier to create test doubles for DbContext and DbSet.
  • Features that come for free - These are capabilities that are part of the core. You don’t even have to know they’re there to benefit from them, much less learn any new coding. This group includes features such as performance gains brought by a rewritten view-generation engine and query compilation modifications, stability granted by the ability of DbContext to use an already open connection, and a changed database setting for SQL Server databases created by Entity Framework.
  • DbContext can now be created with a DbConnection that is already opened - which enables scenarios where it would be helpful if the connection could be open when creating the context (such as sharing a connection between components where you can not guarantee the state of the connection).


Top Reasons To Choose Entity Framework 6 Hosting

  • Fast and Secure Server - Our powerfull servers are especially optimized and ensure the best Entity Framework 6 performance. We have best data centers on three continent, unique account isolation for security, and 24/7 proactive uptime monitoring.
  • Best and Friendly Support - Our support team is extremely fast and can help you with setting up and using Entity Framework 6 on your account. Our customer support will help you 24 hours a day, 7 days a week and 365 days a year.
  • Dedicated Application Pool - With us, your site will be hosted using isolated application pool in order to meet maximum security standard and reliability.
  • Uptime & Support Guarantees - We are so confident in our hosting services we will not only provide you with a 30 days money back guarantee, but also we give you a 99.9% uptime guarantee.
  • World Class Control Panel - We use World Class Plesk Control Panel that support one-click installation.

So, you'll get the best, cheap and reliable Entity Framework 6 hosting with us. Why wait longer?



Free ASP.NET 4.5.1 Hosting - ASPHostPortal :: How To Create and Delete Cookies Using ASP.NET

clock December 10, 2013 06:24 by author Ben

Cookies is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path.  Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines that you created in ASP.NET.
Cookies could be stolen by hackers to gain access to a victim's web account. Even cookies are not software and they cannot be programmed like normal executable applications. Cookies cannot carry viruses and cannot install malware on the host computer. However, they can be used by spyware to track user's browsing activities.

How to create a cookie?
There are many ways to create cookies, I am going to outline some of them below:
Example 1:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);


Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";


How to delete cookie?
Now look at the code given below which will delete cookies.
Example 1:
string User_Name = string.Empty;
string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;

Example 2:
string User_name = string.Empty;
string User_color = string.Empty;
HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}


When we make request from client to web server, the web server process the request and give the lot of information with big pockets  which will have Header information, Metadata, cookies etc., Then repose object can do all the things with browser.

Cookie's common property:

  • Domain => Which is used to associate cookies to domain.
  • Secure  => We can enable secure cookie to set true(HTTPs).
  • Value    => We can manipulate individual cookie.
  • Values  => We can manipulate cookies with key/value pair.
  • Expires => Which is used to set expire date for the cookies.


Advantages of Cookie:

  • Its clear text so user can able to read it.
  • We can store user preference information on the client machine.
  • Its easy way to maintain.
  • Fast accessing.
  • Disadvantages of Cookie
  • If user clear cookie information we can't get it back.
  • No security.
  • Each request will have cookie information with page.


How to clear the cookie information?
we can clear cookie information from client machine on cookie folder

To set expires to cookie object
userInfo.Expires = DateTime.Now.AddHours(1);
It will clear the cookie with one hour duration.


Our Special ASP.NET 4.5.1 Hosting Complete Features

  1. 24/7 Monitoring, We do 24/7 monitoring of your ASP.NET to make sure that we proactively kill any trouble. This helps to ensure maximum uptime and performance.
  2. Easy-to-use service (1-click installs), ASPHostPortal.com gives you access to all SimpleScripts features, provides easy one-click installation and management of all popular applications.
  3. Fast and Secure Server, Our powerfull servers are especially optimized and ensure the best ASP.NET 4.5.1 performance. We have best data centers on three continent and unique account isolation for security.
  4. Daily Backup Service, We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it.



ASP.NET 4.5 Hosting with ASPHostPortal.com :: How to Send E-mail using ASP.NET 4.5

clock December 7, 2013 11:41 by author Mike

If you build a large site then you will be required to provide a facility for the users to contact the relevant department or web master through online form. This is the best way to prevent spam messages as users will not know the real e-mail id. The whole process of sending emails from an ASP.NET form has been simplified with the release of .NET Framework 4.5.

Look at the below figure where I added few Textbox controls.


Figure_1


You need to substitute FROM EMAIL ID, MAIL SERVER NAME, EMAIL ID and PASSWORD on the below code with relevant correct values.

Copy the code given below after providing correct values as mentioned above using Notepad, save it as an .aspx file and upload to your web server. The below code requires access to a shared Windows hosting server with ASP.NET 4.5:

<%@ Page Language="VB" %>
<%@ Import Namespace = "System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
 
<script runat="server">  
 
    Protected Sub btnSubmit_Click1(sender As Object, e As EventArgs)
        Dim mail As New MailMessage()
 
        mail.To.Add(txtEmail.Text)
        mail.From = New MailAddress("FROM EMAIL ID")
        mail.Subject = "Contact Form"
 
        mail.Body = txtName.Text & vbCrLf & txtComments.Text
 
        Dim smtp As New SmtpClient("MAIL SERVER NAME")
        smtp.Credentials = New NetworkCredential("EMAIL ID", "PASSWORD")
 
        smtp.Send(mail)
        lblStatus.Text = "Your data has been submitted successfully"
        txtName.Text = ""
    txtEmail.Text = ""
    txtComments.Text = ""
 
    End Sub
</script>
 
<html>
 
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Contct Form Demo</title>
</head>
 
<body>
    <form id="form1" runat="server">
        Name -
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <br />
        <br />
        Email -
        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
         <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
 
ErrorMessage="Please Enter Valid Email ID" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)
 
*"></asp:RegularExpressionValidator>
        <br />
        <br />
        Comments -
        <asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="71px" Width="301px"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="lblStatus" runat="server"></asp:Label>
        <br />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click1" />
        <br />
        <br />
    </form>
</body>
</html>

Figure_2

In the above code, I have enabled validation for E-mail ID field. This means that if you forgot to enter e-mail id in correct format you will not be able to submit the form.

Looking for quality ASP.NET 4.5 Hosting? Look no further than ASPHostPortal.com Hosting!



BlogEngine .NET 2.8 Hosting, Latest Version of BlogEngine .NET

clock December 4, 2013 09:09 by author Mike

BlogEngine.NET 2.8 is an open source .NET blogging project that was born out of desire for a better blog platform. A blog platform with less complexity, easy customization and one that takes advantage of the great features in .NET.

BlogEngine.NET 2.8 is easily customizable with have many downloadable themes, widgets, and extensions or you could make your own with some basic .NET skills. With BlogEngine.NET, it is easy to make your blog look and function exactly how you’d like.

BlogEngine.NET 2.8 Features
Here's a short list of all the features of BlogEngine.NET 2.8:

  • Plug 'n play - BlogEngine.NET is very easy to setup and customize. To make it work, just upload the files to an ASP.NET 4.0 webserver and you’re ready to start writing. No database configuration, just plug 'n play.
  • Full featured - BlogEngine.NET comes with all the features you would expect from a modern blog engine as well as new unique features such as AJAX comments and screenshot trackbacks.
  • Web 2.0 - BlogEngine.NET features social bookmarks, OpenSearch support, XFN tags, AJAX, FOAF, SIOC, APML, Gravatars, coComments, tag cloud, Google sitemap and other so called Web 2.0 features.
  • Referrer stats - The referrer statistics enables you to see which websites link to you, so you can follow up with comments or just to have fun. This feature is a real time killer that you cannot live without.
  • Cool widgets - There is a variety of cool widgets that such as an AJAX post calendar or a blogroll that automatically retrieves the latest posts from each blog and displays the title beneath the blog. Most of the controls are configurable from the admin section.
  • Advanced comment system - Comments are a very important part of a blog, so BlogEngine.NET features a very advanced commenting system in AJAX that supports country flags, live preview, Gravatars, coComments – all of which can easily be modified in the admin section.
  • Full syndication suite - BlogEngine.NET supports syndication feeds in any possible location. You can find feeds on comments, categories, authors and a main feed. Both RSS 2.0 and ATOM 1.0 are fully supported.
  • Trackbacks and pingbacks - All outgoing links from the posts is tracked- and pinged back, so your blog will get listed in the comments on the linked website if it supports it. When a new post is created, BlogEngine.NET automatically pings Technorati, Feedburner, Ping-o-Matic etc.
  • Search - The search capability of BlogEngine.NET is one of the most advanced and it even allows the visitors to search in the comments. Everything about the search can be configured in the admin section.
  • Standalone pages - Besides regular blog posts, BlogEngine.NET supports the creation of static pages that exist outside the blog chronology. Pages are useful for all kinds of information about you or your blog.
  • Multi-author support - BlogEngine.NET fully supports multiple authors to write posts on the same blog. Visitors are then able to subscribe to the individual author’s RSS feed or view only the posts from their favourite author.
  • Cool themes - BlogEngine.NET comes with some very cool themes for you to choose from. If you want to modify or create a new theme you can do so easily with just a basic understanding of HTML and CSS.
  • XHTML compliance - All the controls in BlogEngine.NET are 100% XHTML 1.0 compliant. All posts you write automatically become compliant thanks to the tinyMCE text editor.
  • Extendable - BlogEngine.NET is built from the ground up using nothing but C# and ASP.NET 4.0 all with simplicity in mind. It means that you can write new controls and themes by using the skills you already have as a .NET developer.


IIS Hosting - ASPHostPortal.com :: Using SSL in ASP.NET Web API

clock December 3, 2013 12:02 by author Mike

SSL works on the public-private key encryption and requires an SSL Certificate on the server. SSL certificates come in different flavors and normally some third party agency issues them to you. Once obtained you need to enable and install the certificate on your web server. For the sake of testing you can create a test certificate in IIS or you can also use IIS Express SSL URL for the communication. Let's quickly see how both of these options can be used.

Using SSL in IIS

Let's first see how to create a test certificate in IIS. Open IIS manager and select the server under the connections pane. Locate Server Certificates in the Features view and double click on it.Server Certificates.

Server Certificates

Server Certificates

Then click on the "Create Self-signed Certificate" link from the actions page to open a dialog as shown below:

Create Self-Signed Certificate
Create Self-Signed Certificate

Enter some friendly name for the certificate and click on OK. You should now have an entry for this new certificate under Server Certificates.

Your New Certificate
Your New Certificate

Notice that in addition to your newly created certificated there is already an entry for IIS Express Development Certificate.

Next, select the website where you wish to install the certificate and click on the Bindings option under the Edit site section of the Action pane. Add HTTPS binding using the newly created certificated as shown below:

Add Site Binding
Add Site Binding

Keep the default port number unchanged, select your certificate name in the SSL certificate dropdownlist. Click OK to close the dialog.

Using SSL in IIS Express

If you are using IIS Express as the development server, things are quite easy. Just select the project in the Solution Explorer and press F4 to open its Properties window.

Project Properties
Project Properties

Set the SSL Enabled property to True. Setting SSL Enabled to True will reveal the SSL URL. In this case it is https://localhost:44300/. You should use this URL while making Web API calls.

Forcing Requests to Use SSL

In many cases you will have both HTTP and HTTPS bindings to your website and you may want to ensure that Web API is called only over HTTPS. To accomplish this task you need to create a custom authorization filter. So, add a class in the Web API project, name it as UseSSLAttribute. Inherit UseSSLAttribute class from AuthorizationFilterAttribute class. The following code shows the completed UseSSLAttribute class:

 public class UseSSLAttribute:AuthorizationFilterAttribute
{
  public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
  {
    if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
    {
      HttpResponseMessage msg = new HttpResponseMessage();
      msg.StatusCode = HttpStatusCode.Forbidden;
      msg.ReasonPhrase = "SSL Needed!";
      actionContext.Response = msg;
    }
    else
    {
      base.OnAuthorization(actionContext);
    }
  }
}

As you can see the UseSSLAttribute class overrides the OnAuthorization() method of the AuthorizationFilterAttribute. Inside the OnAuthorization() method the current scheme of the incoming request is checked using the RequestUrl.Scheme property. If the scheme is anything other than Uri.UriSchemeHttps a new HttpResponseMessage is constructed. The StatusCode property of the response message is set to Forbidden indicating that the server refused to process the request. The ReasonPhrase includes a short phrase describing the reason for refusal. This text will be displayed to the end user via jQuery code in case HTTPS is not used to access the Web API. Finally, the Response property of the actionContext parameter is set to the newly constructed message.

Now you can decorate the Web API action methods using the UseSSL attribute. The following  code shows a GetColors() method that has [UseSSL] attribute applied.

public class ColorController : ApiController
{
  [UseSSL]
  public IEnumerable<string> GetColors()
  {
    return new string[] { "Blue", "Red", "Yellow" };
  }
}

To call the GetColors() method you can use the following jQuery code from a view.

$(document).ready(function () {
  $("#button1").click(function () {
    var options = {};
    options.url = "/api/color";
    options.type = "GET";
    options.contentType = "application/json";
    options.success = function (result) { alert(result); };
    options.error = function (err) { alert(err.statusText); };
    $.ajax(options);
  });
});

 

The above code assumes that the Index view has a button with ID button1 and clicking on the button will invoke the Web API. As you can see the URL is set to /api/color. The type is GET. The success function simply displays the return value of GetColors() method using an alert dialog. Similarly the error function displays the statusText of the err object using an alert dialog. If you run the application and try to invoke the above code over HTTP you will get an error as shown below:

Error Message
Error Message

Now switch to the HTTPS URL - https://localhost:44300/ - as mentioned earlier and try invoking the same code again. While using SSL your browser may give you a warning as shown below:

Warning Message
Warning Message

This warning is issued since you are using a test certificate. Click on the Continue to this website option and invoke the code. This time you should get the color values successfully.

Color Values
Color Values


If your website deals with sensitive data it is recommended to use Secure Sockets Layer or SSL. SSL establishes an encrypted channel of communication between the server and client browser. To use SSL you must install a server side certificate. For the sake of testing you can create a test certificate using IIS or use an inbuilt mechanism of IIS Express. To enforce SSL on Web API you can create a custom authorization filter that checks the request scheme. If the scheme is HTTPS only then the call is processed, otherwise an error is sent to the client.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in