All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

ASP.NET Hosting :: How to Setup URL Redirection

clock November 15, 2018 07:07 by author Jervis

We have so many clients asking about this issue. So, we decide to write this tutorial and hope this information can help other people too. In this review, we will write simple tutorial about how to setup http/https redirection in IIS.

There are lots of routing options accessible in ASP.NET but still it comes a time when you need to manipulate a URL and manipulating it outside a code comes handy. When this happens, the best you can do id to use IIS Rewrite Module. Transforming various URL’s out of code enables you to do various things including performing redirections for archive or transferred content without interfering with the code, you can easily implement SEO optimizations and tweaks quickly and easily without code and many more. Below is a collection of useful IIS rewrite rules that will help you understand IIS rewrites.

Useful IIS Rewrite Rules

Adding www Prefix

This is a basic rule that adds prefix “www” to any URL you need. This is a requirement for SEO.

Redirection from Domain 1 to Domain 2

This rule comes handy when you change the name of your site or may be when you need to catch and alias and direct it to your main site. If the new and the old URLs share some elements, then you could just use this rule to have the matching pattern together with the redirect target being.

HTTPS/HTTP Redirection

Redirecting users from HTTP to HTTPS is one of the reasons that you need to apply useful IIS rewrite rules. It can lead to conditional statements while looking for dev/test mode in your code. This rules allows you to handle the redirection without much statements which is tidier.

There is a pair of rules in this case each for one of the two ways. In both the rules, a check is performed to verify that the protocol used is http/https. The rules work on the same URL patterns or the similar lists of pages to match. For the redirect to HTTP, it is not about matching the pages; it is a reverse of the first rule and usually have a number of .NET/site paths that are excluded.

Setup Redirection Using IIS

Above steps is to setup URL redirection via your code. But, if you manage your own server, you can also setup redirection via IIS. The following is the steps

1. Download and install the “URL Rewrite” module.

2. Open the “IIS Manager” console and select the website you would like to apply the redirection to in the left-side menu:



3. Double-click on the “URL Rewrite” icon.

4. Click “Add Rule(s)” in the right-side menu.

5. Select “Blank Rule” in the “Inbound” section, then press “OK”:

6. Enter any rule name you wish.

7. In the “Match URL” section:

- Select “Matches the Pattern” in the “Requested URL” drop-down menu 
- Select “Regular Expressions” in the “Using” drop-down menu 
- Enter the following pattern in the “Match URL” section: “(.*)” 
- Check the “Ignore case” box

 

 

8. In the “Conditions” section, select “Match all” under the “Logical Grouping” drop-down menu and press “Add”.

9. In the prompted window:

- Enter “{HTTPS}” as a condition input 
- Select “Matches the Pattern” from the drop-down menu 
- Enter “^OFF$” as a pattern 
- Press “OK”

10. In the “Action” section, select “Redirect” as the action type and specify the following for “Redirect URL”:

https://{HTTP_HOST}/{R:1}

11. Check the “Append query string” box.

12.Select the Redirection Type of your choice. The whole “Action” section should look like this:

 

NOTE: There are 4 redirect types of the redirect rule that can be selected in that menu: 

- Permanent (301) – preferable type in this case, which tells clients that the content of the site is permanently moved to the HTTPS version. Good for SEO, as it brings all the traffic to your HTTPS website making a positive effect on its ranking in search engines. 
- Found (302) – should be used only if you moved the content of certain pages to a new place *temporarily*. This way the SEO traffic goes in favour of the previous content’s location. This option is generally not recommended for a HTTP/HTTPS redirect. 
- See Other (303) – specific redirect type for GET requests. Not recommended for HTTP/HTTPS. 
- Temporary (307) – HTTP/1.1 successor of 302 redirect type. Not recommended for HTTP/HTTPS.

13. Click on “Apply” on the right side of the “Actions” menu.

The redirect can be checked by accessing your site via http:// specified in the URL. To make sure that your browser displays not the cached version of your site, you can use anonymous mode of the browser.

The rule is created in IIS, but the site is still not redirected to https://

Normally, the redirection rule gets written into the web.config file located in the document root directory of your website. If the redirection does not work for some reason, make sure that web.config exists and check if it contains the appropriate rule.

To do this, follow these steps:

1. In the sites list of IIS, right-click on your site. Choose the “Explore” option:

 

2. “Explore” will open the document root directory of the site. Check if the web.config file is there.

3. The web.config file must have the following code block:

<configuration> 
<system.webServer> 
<rewrite> 
<rules> 
<rule name="HTTPS force" enabled="true" stopProcessing="true"> 
<match url="(.*)" /> 
<conditions> 
<add input="{HTTPS}" pattern="^OFF$" /> 
</conditions> 
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> 
</rule> 
</rules> 
</rewrite> 
</system.webServer> 
</configuration>

4. If the web.config file is missing, you can create a new .txt file, put the aforementioned code there, save and then rename the file to web.config.

 

 



ASP.NET Core Hosting :: How to Fix Error "An error occurred while starting the application" in ASP.NET Core

clock November 9, 2018 09:43 by author Jervis

Previously, we have written tutorial about how to fix 502.5 error that you face when publishing your ASP.NET Core application. Another issue that you might face when publishing your .net Core application is:

“An error occurred while starting the application.  .NET Framework <version number> | Microsoft.AspNetCore.Hosting version <version number> | Microsoft Windows <version number>”

It looks like:

What happened?

It basically means something really bad happened with your app.  Some things that might have gone wrong:

  • You might not have the correct .NET Core version installed on the server.
  • You might be missing DLL’s
  • Something went wrong in your Program.cs or Startup.cs before any exception handling kicked in

Event Viewer (Probably) Won’t Show You Anything

If you’re running on Windows and behind IIS, you might immediately go to the Event Viewer to see what happened based on your previous ASP.NET knowledge.  You’ll notice that the error is not there.  This is because Event Logging must be wired up explicitly and you’ll need to use the Microsoft.Extensions.Logging.EventLog package, and depending on the error, you might not have a chance to even catch it to log to the Event Viewer.

How to figure out what happened (if running on IIS)

Instead of the Event Viewer, if you’re running behind IIS, we can log the request out to a file.  To do that:

  1. Open your web.config
  2. Change stdoutLogEnabled=true
  3. Create a logs folder
    - Unfortunately, the AspNetCoreModule doesn’t create the folder for you by default. If you forget to create the logs folder, an error will be logged to the Event Viewer that says: Warning: Could not create stdoutLogFile \\?\YourPath\logs\stdout_timestamp.log, ErrorCode = -2147024893.
    -
    The “stdout” part of  the value “.\logs\stdout” actually references the filename not the folder.  Which is a bit confusing.
  4. Run your request again, then open the \logs\stdout_*.log file

Note – you will want to turn this off after you’re done troubleshooting, as it is a performance hit.

So your web.config’s aspNetCore element should look something like this

 <aspNetCore processPath=”.\YourProjectName.exe” stdoutLogEnabled=”true” stdoutLogFile=”.\logs\stdout” />

Doing this will log all the requests out to this file and when the exception occurs, it will give you the full stack trace of what happened in the \logs\stdout_*.log file

 

Hope this helps. In case, you need ASP.NET Core hosting, you can always try our services start from $1.00/month.



ASP.NET Core 2 Hosting :: How to Fix Error 502.5 When Deploy Your ASP.NET Core

clock November 7, 2018 08:25 by author Jervis

I decide to make this tutorial as most of our users also experience same problem when deploying their ASP.NET Core application.

I recently hit this problem after manually modifying the web.config file. Fortunately, the problem is easy to fix.

In this post, we see two different causes of this error, two different solutions for the first cause, a solution for the second cause, and learn what needs to be in web.config for ASP.NET Core to operate.

The Error

Here is a screenshot of the HTTP Error 502.5 - Process Failure error. You'll see this, in your browser, when making a request to your ASP.NET Core application, after deployment, if you have this issue.

Why do I get the error?

 

The HTTP Error 502.5 - Bad Gateway and HTTP Error 502.5 - Process Failure error messages occur in ASP.NET Core when IIS fails to execute the dotnet process.

I've seen this error happen for two different reasons:

  • .NET Core Runtime is not installed
  • web.config file has not been transformed

How to Fix This Error?

This is very simple and easy to fix this issue. What you need to make sure is that your hosting provider support or already installed the latest ASP.NET Core on their hosting environment.

1. Install Latest .NET Core Runtime

You can download the latest .NET Core runtime from Microsoft's .NET download page.

For Windows, you'll usually want the latest .NET Core runtime (currently v2.1.1), as highlighted in the following screenshot:

This will get you the Windows Hosting Bundle Installer, which will install both the x86 and x64 runtimes on Windows Server.

2. Publish a Self-Contained Deployment

If you don't want to install the .NET Core Runtime. An alternative for .NET Core web applications is to publish them in the Self-Containeddeployment mode, which includes the required .NET Runtime files alongside your application.

You can select this option from the advanced publish settings screen in Visual Studio: 

If you go with this option, you'll also need to choose a target runtime: win-x86, win-x64, osx-x64, or linux-x64. Because self-contained deployments are not portable.

3. Transform your web.config file

Another reason for this error to occur is when you deploy an untransformed web.config file. This is likely to be your issue if you had a previously working web application and merely deployed a new version of it.

ASP.NET Core Web Config

In ASP.NET Core applications, the web.config file contains a handler that directs requests to the AspNetCoreModule and an aspNetCoreelement that defines and configures the ASP.NET Core process to execute your web application.

Here is a minimal web.config file for an ASP.NET Core application:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 
<system.webServer>
   
<handlers>
     
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
   
</handlers>
   
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="true"
       
stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
 
</system.webServer>
</configuration>

Note that it's possible that you don't have a web.config file in your ASP.NET Core project. If you do not, one will be generated for you when publishing the project, as IIS and IIS Express require a web.config file when hosting an ASP.NET Core web app.

The Issue

The untransformed web.config contains the variables %LAUNCHER_PATH% and %LAUNCHER_ARGS% rather than the correct paths. When IIS tries to run ASP.NET Core, it uses %LAUNCHER_PATH% and %LAUNCHER_ARGS% rather than the correct path and arguments.

To fix the HTTP Error 502.5 in ASP.NET Core, you need to transform the web.config and replace the untransformed web.config file on the IIS web server.

How do I transform web.config?

This transformation takes place when you choose to publish your web application. The transformed web.config ends up in the published output folder. Therefore, you simply need to publish your web application and copy the resulting web.config file onto the server.

In a transformed web.config file, the aspNetCore element will look something like this:

<aspNetCore processPath="dotnet" arguments=".\MyApplication.dll" stdoutLogEnabled="true"
    stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />

%LAUNCHER_PATH% has been replaced by dotnet and %LAUNCHER_ARGS% has been replaced by the path to the main web application dll .\MyApplication.dll.



ASP.NET Core 2 Hosting :: How to Create Simple Shoutbox Using ASP.NET Core Razor Pages

clock November 6, 2018 10:44 by author Jervis

ASP.NET Core 2 comes with Razor Pages that allow developers to build simple web applications with less overhead compared to MVC. The emphasis is on the word “simple” as Razor Pages doesn’t come with patterns suitable for bigger and more complex applications. For this, we have MVC that is flexible enough to build applications that will grow over years. This blog post uses a simple shoutbox application to illustrate how to build applications using Razor Pages.

Shoutbox Application

This post introduces how to build a simple and primitive shoutbox application using ASP.NET Core and Razor Pages. We will also use SQL Server LocalDb and Entity Framework Core code-first to make things more interesting. The goal of this post is to demonstrate how to use Razor Pages pages with and with-out a backing model.

We will build a fully functional application you can use to further dig around and discover the secrets of Razor Pages.

Creating a Razor Pages Application

Let’s start with a new ASP.NET Core Razor Pages project. Yes, now there is a new template for this. 

 

Razor Pages projects have a similar structure to MVC ones, but, as there are some differences, like Pages folder, and as Razor Pages doesn’t have controllers, we don’t have a controllers folder. Also, there’s no folder for views.

Database, Data Context, and Shoutbox Entity

We will use SQL Server LocalDB as our database and we will go with Entity Framework Core code-first. The first thing to do is to modify appsettings.json and add a connection string: I leave everything else like it is.

{
  "ConnectionStrings": {
    "ShoutBoxContext": "Server=(localdb)\\mssqllocaldb;Database=ShoutBoxContext;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }

Let’s also create a simple entity class for our shoutbox item. As we don’t create model mappings we have to use data annotations to let the data context know how to create a database table.

public class ShoutBoxItem
{
    [Key]
    public int Id { get; set; }
    [Required]
    public DateTime? Time { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Message { get; set; }
}

To communicate with the database we need a database context class too. We keep our database context as minimal as reasonably possible.

public class ShoutBoxContext : DbContext
{
    public ShoutBoxContext(DbContextOptions<ShoutBoxContext> options) : base(options)
    { }
    public DbSet<ShoutBoxItem> ShoutBoxItems { get; set; }
}

Finally, we need to introduce our database context to a framework-level dependency injection mechanism. We can do this with the ConfigureServices()method of the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDbContext<ShoutBoxContext>(options => {n
        options.UseSqlServer(Configuration.GetConnectionString("ShoutBoxContext"));
    });
    services.AddTransient<ShoutBoxContext>();
}

Before using the database, we must ensure it is there and available. For this, we add an EnsureCreated()call to the ends of the Configure() method of the Startup class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
    app.ApplicationServices.GetRequiredService<ShoutBoxContext>()
                           .Database
                           .EnsureCreated();
}

Now we have everything we need to start building the user interface for our simple shoutbox application.

Building Shout List

Our simple application will show the 100 latest shouts as a list on the front page. This view is an example of a page with no code-behind file. All the work is done on the page itself. We will use it to get our data context to the page.

@page
@inject RazorPagesShoutBox.Data.ShoutBoxContext dataContext
@{
    ViewData["Title"] = "Home Page";
    var shouts = dataContext.ShoutBoxItems
                            .OrderByDescending(s => s.Time)
                            .Take(100)
                            .ToList();
}
<h2>@ViewData["Title"]</h2>
<div class="row">
    <div class="col-md-10">
        @if (shouts.Any())
        {
            foreach (var shout in shouts)
            {
                <p>
                    <strong>@shout.Name</strong> | @shout.Time.ToString()<br />
                    @Html.Raw(shout.Message.Replace("\r\n", "<br />"))
                </p>
            }
        }
        else
        {
            <p>No shouts... be the firts one!</p>
        }
    </div>
</div>
<a href="AddShout">Add shout</a>

At the end of the page, we have a link to the page where the user can add a new shout.

Building New Shout Form

To let users shout, we create a separate page and this time we will use code-behind file where the model for the page is defined. Notice the @model directive in the page code.

@page
@model AddShoutModel
@{
    ViewData["Title"] = "Add shout";
}
<h2>@ViewData["Title"]</h2>
<div class="row">
    <div class="col-md-10">
        <form method="post">
            <div class="form-group">
                <label asp-for="Item.Name"></label>
                <input class="form-control" asp-for="Item.Name" />
                @Html.ValidationMessageFor(m => m.Item.Name)
            </div>
            <div class="form-group">
                <label asp-for="Item.Message"></label>
                <textarea class="form-control" asp-for="Item.Message"></textarea>
                @Html.ValidationMessageFor(m => m.Item.Message)
            </div>
            <input type="hidden" asp-for="Item.Time" />
            <button type="submit" class="btn-default">Shout it!</button>
        </form>
    </div>
</div>

All models that support pages are inherited from the PageModel class. We use constructor injection to get our data context to the page model. The model we want to show on the page is represented by Item property. The BindProperty attribute tells ASP.NET Core that data from the form must be bound to this property. Without it, we must write code to extract values from the request and do all the dirty work by ourselves. The OnGet() method of the page model is called when the page is loaded using the HTTP GET method and OnPost() is called when a POST was made.

public class AddShoutModel : PageModel
{
    private readonly ShoutBoxContext _context;
    public AddShoutModel(ShoutBoxContext context)
    {
        _context = context;
    }
    [BindProperty]
    public ShoutBoxItem Item { get; set; }
    public void OnGet()
    {
        if (Item == null)
        {
            Item = new ShoutBoxItem();
        }
        Item.Time = DateTime.Now;
    }
    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        Item.Id = 0;
        _context.ShoutBoxItems.Add(Item);
        _context.SaveChanges();
        return RedirectToPage("Index");
    }
}

It’s time to run the application and make some serious shouts!

Wrapping Up

Razor Pages provides us with a thinner model to build applications and it’s suitable for small applications. As it is part of ASP.NET Core MVC, it supports many features that come with MVC. The PageModel is like a mix of models and controllers in MVC and its purpose is to provide the separation of presentation and logic. We can use Razor Pages to build pages with or without a backing model and it is completely up to us to decide which way to go. 



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

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

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

Tag cloud

Sign in