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 Hosting - ASPHostPortal.com :: How To Using DataAnnotations and Localization in ASP.NET Core MVC

clock March 14, 2017 05:54 by author Armend

Using DataAnnotations and Localization in ASP.NET Core MVC

This article shows how ASP.NET Core localization can be used together with data annotations. The data annotations are used to decorate the data model, and when HTTP POST/PUT (also PATCH) Requests are sent with model errors, the error message is returned localized in the request culture.

Localization Setup

In the Startup class, the AddDataAnnotationsLocalization is added in the ConfigureServices method.   

services.AddMvc()
   AddViewLocalization()
   AddDataAnnotationsLocalization();

Now a model class can be created and the data annotations can be used. The Length property in this example has a range attribute, with an ErrorMessageResourceName and an ErrorMessageResourceType property set. The ErrorMessageResourceType is used to define the resource itself using the type and the ErrorMessageResourceName is used to define the resource identifier. Only the Length property has localized error messages implemented.

using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Globalization;
using AspNet5Localization.Controllers;
using Microsoft.Extensions.Localization;  
namespace AspNet5Localization.Model
{
    public class Box
    {
        public long Id { get; set;
        public double Height { get; set;
        public double Width { get; set; }
        [Required(ErrorMessage = "BoxLengthRequired")]
        [Range(1.0, 100.0, ErrorMessage = "BoxLengthRange")]
        public double Length { get; set; }
    }
}

Now a MVC 6 controller can be created which uses the model class. This controller implements POST and PUT action methods, which uses the ModelState to validate the request. If the model is invalid, the error message is returned with a localized value.

using AspNet5Localization.Model;
using Microsoft.AspNetCore.Mvc;
namespace AspNet5Localization.Controllers
{
    [Route("api/[controller]")]
    public class BoxesController : Controller
    {
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            if (id == 0)
            {
                return NotFound(id);
            }
            return Ok(new Box() { Id = id, Height = 10, Length = 10, Width=10 });
        }
 
        /// <summary>
        /// http://localhost:5000/api/boxes?culture=it-CH
        /// Content-Type: application/json
        ///
        /// { "Id":7,"Height":10,"Width":10,"Length":1000}
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post([FromBody]Box box)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            else
            {          
                string url = Url.RouteUrl("api/boxes", new { id = 11111 },
                    Request.Scheme, Request.Host.ToUriComponent());
 
                return Created(url, box);
            }
        }
 
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody]Box box)
        {
            if(id == 0)
            {
                return NotFound(box);
            }
 
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            else
            {
                return Ok(box);
            }
        }
 
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            if (id == 0)
            {
                return NotFound(id);
            }
 
            return new NoContentResult();
        }
    }
}

Now the POST method can be called in Fiddler or Postman. Underneath is an example of a HTTP POST Request using the it-CH culture. The length property is outside the range and will return an model state error.

http://localhost:5000/api/boxes?culture=it-CH
User-Agent: Fiddler
Host: localhost:5000
Content-Length: 46
Content-Type: application/json
{ "Id":7,"Height":10,"Width":10,"Length":1000}
HTTP Response with a it-CH localized error message:
HTTP/1.1 400 Bad Request
Date: Sat, 24 Oct 2015 17:15:28 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
{"Length":["The box length should be between 1 and a 100 it-CH"]}

Localization can be used in data annotations like previous versions of MVC or Web API and provides a simple way of validating your data inputs.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Improve Performance of an ASP.NET Website

clock March 7, 2017 04:49 by author Armend

Improve Performance of an ASP.NET Website

In this tip, we will look at various aspects of improving the performance of ASP.NET web applications.
Performance is an important aspect of the modern day web application development. Here are some tips that you can consider while making a better performing website.

1. Upgrade Your ASP.NET Framework

Check your .NET framework. If you can upgrade your site to use .NET 4.5, then it has some great performance optimizations. .NET 4.5 has a new Garbage Collector which can handle large heap sizes (i.e., tens of gigabytes). Some other improvements are Multi-core JIT compilation improvements, and ASP.NET App Suspension. These optimizations do not require code changes.

2. Caching

Use output caching – Use output caching for regularly used views or pages which have no dynamic updates. The easiest way to implement cache on MVC view is to add an [OutputCache] attribute to either an individual controller action or an entire controller class. Here is a controller action Index() that will be cached for 15 seconds.

[OutputCache(Duration = 15, VaryByParam = "None")]
public ActionResult Index(string Id)
{
}

Use Data caching - Reduces the database or the disk I/O by caching the regularly used data to in-memory cache. This avoids repeated queries for data, and it can improve performance and scalability. In addition, caching makes data available when the data source is temporarily unavailable. The .NET Framework provides classes that enable you to use caching facilities in ASP.NET applications. These classes are defined in the System.Runtime.Caching namespace.

3. Always keep CSS and JavaScript External

Never add any JavaScript or inline style information within the views. That would regenerate the view each time and you would miss out on the benefits of the Caching. Hence always keep JS and CSS as separate files and add them as links in the view.

4. File Compression

There are often requests to the web server with lot of static content. These contents can be compressed thereby reducing the bandwidth on requests. The following setting is only available in II7 and later.

configuration> 
    <system.webServer>   
        <urlCompression doStaticCompression="true" doDynamicCompression="true" /> 
    </system.webServer>

The urlCompression name sounds strange but it is not really the compressing of URLs. It means compressing or gzipping the content that is sent to the browser. By setting to true/enabling, you can gzip content sent to the browser while saving lots of bandwidth.

5. Bundling and Minification

The custom CSS files and the JavaScript files should be bundled into a single large file (reduces the number of HTTP requests) and also minified (reduces the size of the data transferred over the wire).

6. CDN (Content Delivery Network)

All the 3rd party JavaScript files such as JQuery, Knockout should always use the CDN instead of the web application server. CDN Servers are dedicated to deliver the static content and is always faster than your own host. There is a very high probability that the client (browser) would have already cached the JavaScript as part of other web application since most of them use the same CDN URL.

7. Control Image Requests

There are couple of ways to do this. 

Image sprite - With image sprite, you can combine multiple different images into a single large image. Then use CSS to reposition those images within the site.
Base64 Data URIs - With this option, you would never make any requests to the server to obtain any images.

8. Script Rendering Order

Move the script tags <script> to the very bottom of the page. The reason this is important is because during the rendering, when the browser comes across a <script> tag, it stops to process the script and then moves ahead. If you put the script tags at the bottom of the page, the page/HTML will render faster and the scripts can execute after the DOM elements have loaded. Sometimes moving the script to the bottom of the page is not possible as some DOM elements or CSS may depend on these scripts, so they can be rendered. In such cases, you could move those scripts further up the page.

There are some other ways:

  • 1.defer attribute

Hide Copy Code

<script src="some.js" defer>
</script>

Using the defer attribute, you can specify the script not to run until the page has been fully loaded.

  • 2.async attribute

<script src="some.js" async>
</script>

Using the async tag, the scripts will be run asynchronously, as soon as it is available.

9. Removing Default HTTP Modules in ASP.NET

ASP.NET has many http modules waiting for request to be processed and would go through the entire pipeline even if it’s not configured for your application.
All the default modules will be added in the machine.config place in“$WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG” directory. One could improve the performance by removing those modules which you wouldn’t require.

10. Compile in Release Mode

Always set the build configuration to release mode for the website.

In this tip, we looked at some of the approaches that you can take to make optimized and better performing web sites. This included, reducing number of requests to the server, changes to the .NET framework, and compressing techniques.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Creating Default User Roles in ASP.NET MVC

clock February 28, 2017 05:00 by author Armend

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more.


In this article, We'll look into how to create default user roles in ASP.NET MVC 5. Let's begin by establishing where the user role is assigned, and that is the registration stage. In the default template, you have the AccountController that contains a Register action. The default implementation looks like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}


What's missing here is the role assignment, so let's add that. Right after the CreateUserAndAccount call, we can check whether a specific role exists, and if it is - add the registered user to it. In case the role is new, create it.

if (!Roles.RoleExists("Standard"))
    Roles.CreateRole("Standard");
Roles.AddUserToRole(model.UserName, "Standard");


Here I am working with a role called Standard, but obviously you can use another identifier for it. If you open the database that is carrying the app data, you will notice that there are two new tables introduced in the existing context - Roles and UsersInRoles.

As the data skeleton is established, you can now limit content access based on roles. In views, you could use the Authorize attribute:

[Authorize(Roles = "Admin")]

Or you could check for the role directly:


@if (Roles.GetRolesForUser().Contains("Admin"))
{
}

That's the tutorial How to create Default User Roles in ASP.NET MVC 5, for more information about ASP.NET MVC 5 Hosting please feel free to visit ASPHostPortal.com.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Using Microsoft Enterprise Library in ASP.NET

clock February 21, 2017 05:45 by author Armend

In this tutorial we will show you how to using Microsoft Enterprise Library is a collection of reusable software components used for  logging, validation, data access, exception handling etc.

Here I am describing how to use Microsoft Enterprise Library for data access.

Step 1: First download the project from
http://entlib.codeplex.com/ URL.
Step 2: Now extract the project to get

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ObjectBuilder.dll


And give reference in the Bin directory by Right click on Bin -> Add Reference -> then give the path of these 4 dlls. Then

Step 3: Modification in the web.config for Connection String.

<add name="ASPHostPortalConnection" providerName="System.Data.SqlClient" connectionString="DataSource=ASPHostPortalSQLEXPRESS;Initial Catalog=ASPHostPortal;User ID=sa;Password=admintest;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>


Give the connection string as above where Datasource is your data source name, Initial Catalog is your database name and User ID and Password as in your sql server.

Step 4:

Now it is time to write the code.

Write the below 2 lines in the using block.

using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

Here I am writting some examples how to work on:

public DataTable Read()
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetStoredProcCommand("[Topics_Return]");
            DataSet dataSet = db.ExecuteDataSet(dbCommand);
            return dataSet.Tables[0];
        }
        catch
        {
            return null;
        }
    }


The above code is a sample that will return a dataset. Here Fewlines4bijuConnection is the connection name and Topics_Return is the stored procedure name that is nothing but a Select statement.
But if the stored procedure is taking parameter then the code will be like:

 public int Save()
    {
        Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
        DbCommand dbCommand = db.GetStoredProcCommand("Topics_Save");

        db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");
        db.AddInParameter(dbCommand, "@Description", DbType.AnsiString, "Here is the Descriptiont");      
        db.AddInParameter(dbCommand, "@PostedBy", DbType.Int32, 4);       
        db.AddOutParameter(dbCommand, "@Status", DbType.AnsiString, 255);
        try
        {
            db.ExecuteNonQuery(dbCommand);
            return Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));
        }
        catch
        {
            return 0;
        }
    }

As the code explained above ASPHostPortalConnection is the connection name and Topics_Save is the stored procedure name that is taking 3 (Subject,Description,PostedBy) input parameters and 1(Status) output parameter.

You may give values from textbox, I am here provideing sample values like  "Here is the subject", "Here is the Descriptiont" or you may give the UserID from session, I am here giving 4. The output parameter will give you a string as defined and the code to get the value is

int returnValue=Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));

you can pass input parameter as below

db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");

DbType.AnsiString since Subject is of string time, you can select different values like AnsiString, DateTime from the Enum as be the parameter type.

The above code describes if you are using any stored procedure.
Below is an example that shows how to use inline SQL statements.

public DataSet GetID(string title)
    {
       DataSet ds=new DataSet();

        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetSqlStringCommand("Select * FROM Topics where UserID=1 and
IsDeleted=0");          
            ds= db.ExecuteDataSet(dbCommand);
           return ds;         
        }
        catch
        {
            return ds;
        }
         return ds;
    }


Happy coding!!

 

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core - ASPHostPortal.com :: Centralized ASP.NET Core Logging in One Line of Code

clock February 14, 2017 05:32 by author Armend

Centralized ASP.NET Core Logging in One Line of Code

ASP.NET Core comes with some great built-in logging. Framework components such as Routing, MVC and EntityFramework have been updated to support structured logging throughout - for example, when MVC selects a controller and action it includes ActionName in a log event so that later, you can drill down easily to requests hitting a specific action. The framework also adds convenient properties like RequestId to log events by default, making it trivial to zoom in on just the events raised during handling of a particular HTTP request. Setting up truly great application logging in an ASP.NET app has never been easier.

Seq has had first-class support for ASP.NET Core apps through Serilog since the early beta releases.
Just recently, we've taken this a step further. On File > New Project precious time spent configuring libraries can really add up. We want Seq to be so simple to include that there's no reason to put it off until later. That's why we've created a new package, Seq.Extensions.Logging, that gets centralized logging configuration down to just one line of code.

Seq.Extensions.Logging

Here's all it takes to get a new ASP.NET Core app hooked up to Seq. First, add the package:

"dependencies": {
  "Seq.Extensions.Logging": "1.0.1"
}

Then in your Startup class's Configure() method, call AddSeq():

public void Configure(IApplicationBuilder app, 
                      IHostingEnvironment env,
                      ILoggerFactory loggerFactory)
{
    loggerFactory.AddSeq("http://localhost:5341");

The AddSeq() method supports a few more parameters including the logging level and API key if one is needed. It can also pull configuration from appsettings.json for simple deployment-time configuration.
Once the logger is configured, you will immediately see some events from the framework on each request. You can add logging to your own code by taking a dependency on Microsoft.Extensions.Logging's ILogger<T>:

class HomeController : Controller 
{
    readonly ILogger<HomeController> _log;

    public HomeController(ILogger<HomeController> log)
    {
        _log = log;
    }

    public IActionResult Index()
    {
        var secret = 42;
        _log.LogInformation("The secret number is {Secret}");
    }
}

Notice that ASP.NET Core logging has full support for message templates, meaning tokens like {Secret} in the log message will be translated into fully-searchable properties in Seq.

Under the hood

The API of Seq.Extensions.Logging is complete: you can comfortably use it all the way through to production without thinking about how any of it works under the hood. But, if you find you need more control over how log events are collected, or if you'd like to use more advanced Serilog features to enrich or filter events, it's easy to migrate over to Serilog.
Under the hood, the package wraps Serilog, the Serilog provider for Microsoft.Extensions.Logging, and the other bits and pieces of plumbing that make Seq and Serilog work together. Replacing AddSeq() with AddSerilog() is straightforward and mechanical, and all of your logging will continue working in exactly the same way.

Levelling up

There's a whole host of interesting details on ASP.NET Core's logging in the official documentation. Taking some time to learn how to use the API can make your application much easier to debug once it's out there in production.
Don't forget to Install-Package Seq.Extensions.Logging and AddSeq() next time you're starting out on ASP.NET Core!



ASP.NET Hosting - ASPHostPortal.com :: JavaScript style setTimeout and setInterval in C#

clock January 31, 2017 05:05 by author Armend

I found JavaScript setTimeout and setInterval functions quite handy for timer like functionality and some time wish I could use that in C# too. In an earlier post I create a C# like timer functionality in JavaScript. Now, I want to do opposite i.e. implement JavaScript setTimeout and setInterval like functionality in C#.
This is can be done very easily using Lamda expressions and Timer. Look at the below utility class -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DailyCoding.EasyTimer
{
    public static class EasyTimer
    {
        public static IDisposable SetInterval(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }

        public static IDisposable SetTimeout(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.AutoReset = false;
            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }
    }
}

To use setTimeout this you can simply do -

EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms delay

}, 1000);

The code will run after 1000 ms delay similarly like JavaScript setTimeout. The function also returns a handle. If you want clearTimeout like functionality, then the simply dispose off the handle.

var stopHandle = EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms

}, 1000);


// In case you want to clear the timeout

stopHandle.Dispose();
Similarly you can use setInterval as -
EasyTimer.SetInterval(() =>
{
    // --- You code here ---
    // This piece of code will run after every 1000 ms

}, 1000);

and SetInterval also returns a stop handle which you can use for clearInterval like functionality. Just dispose off the handle -

var stopHandle = EasyTimer.SetInterval(() =>
    {
        // --- You code here ---
        // This piece of code will run after every 1000 ms
        // To stop the timer, just dispose off the stop handle

    }, 1000);


// In case you want to clear the interval
stopHandle.Dispose();

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.




ASP.NET Hosting - ASPHostPortal.com :: How to publish ASP.NET Core web application via Visual Studio 2015

clock November 3, 2016 07:04 by author Armend

How to publish ASP.NET Core web application via Visual Studio 2015

Create a web app
From the Visual Studio Start page, tap New Project.
In the center pane, tap ASP.NET Core Web Application (.NET Core) Create a web app

In the New ASP.NET Core Web Application dialog, tap Web Application, and then tap OK.

 

Login to your hosting control panel --> Websites --> Select the target site --> click Show Web Deploy Info. If you have not enable this feature, please enable it first at the same place. You will able to see the web deploy settings there or download the publishing xml configuration file directly.
And then open your web application with Visual Studio 2015, right click the web application, then click"Publish" to start.
You can chose Import  with Publish XML and Custom to fill in the deploy info.

Click Validate Connections to check the deploy info,then you can tap Publish.

Note:If you get certificate error with publish,please add below code to your PublishProfiles.
<AllowUntrustedCertificate>True</AllowUntrustedCertificate>

 

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice

Save



ASP.NET 5 Hosting - ASPHostPortal.com :: Cookie Based Authentication in ASP.NET 5

clock July 30, 2015 06:27 by author Dan

This post is about cookie based authentication in ASP.NET 5. I am implementing a cookie authentication in ASP.NET MVC application. Similar to other middleware components in ASP.NET, Cookie Authentication is also a middleware component, which you need to plug into ASP.NET pipeline.

For implementing cookie authentication, you require reference of Cookie middleware, here is the project.json file.

{
    "dependencies": {
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.AspNet.Hosting": "1.0.0-beta1",
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
        "Microsoft.AspNet.Security": "1.0.0-beta1",
        "Microsoft.AspNet.Security.Cookies": "1.0.0-beta1",
        "Microsoft.AspNet.StaticFiles": "1.0.0-beta1",
    },
    "commands": {
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
    },
     "frameworks": {
        "aspnet50": {}
  }
}

All the components used in this project are available in ASP.NET Core Framework as well.

Now you need to plug the Cookie authentication module to use in ASP.NET pipeline, you can do this via Startup.cs file.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseErrorPage();
 
        app.UseServices(services =>
        {
            services.AddMvc();
        });
     
        app.UseCookieAuthentication(options => {
            options.LoginPath = new PathString("/Home/Login");
        });
        app.UseMvc();                       
    }       
}

Now, you need to apply the Authorize filter to protect resources, I am applying it in the class level. When there is a unauthorized request to such resource, filter returns 401 and the cookie middleware redirects to /Home/Login.

Note: You need to set the LoginPath property explicitly, otherwise it may not redirect.

[Authorize]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

And here is the Login action method, this code is for illustration purpose only, I not validating against database, if username and password matches the hard coded credentials, identity is established with that username.

[AllowAnonymous]
public IActionResult Login()
{
    return View();
}
 
[HttpPost, AllowAnonymous]
public IActionResult Login(User user)
{
    if(user.UserName == "admin" && user.Password == "Password")
    {
        var claims = new[]
        {
            new Claim("name", user.UserName)
        };
        var identity = new ClaimsIdentity(claims,
            CookieAuthenticationDefaults.AuthenticationType);
        Context.Response.SignIn(identity);
 
        return Redirect("~/");
    }
    else
    {
        ModelState.AddModelError("LogOnError",
            "The user name or password provided is incorrect.");
    }
    return View(user);
}
 
public IActionResult Logout()
{
    Context.Response.SignOut
    (CookieAuthenticationDefaults.AuthenticationType);
    return View("Login");
}

And here is the Login view

@using(Html.BeginForm())
{
    @Html.LabelFor(model => model.UserName)
    @Html.EditorFor(model => model.UserName)
    @Html.LabelFor(model => model.Password)
    @Html.PasswordFor(model => model.Password)
    <input type="submit" value="Sign In" />
    <br/>
    @Html.ValidationMessage("LogOnError")
}

To verify the implementation, install the required packages using kpm restore command, once it finishes, execute k web command. If web server is started, browse http://localhost:5001/, which will redirect to /Home/Login page, where you can enter the credentials, you will redirect back to /Home/Index page.

Best ASP.NET 5 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET MVC hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: 4 Steps to designate appropriate permissions to App_Data folder of WebMail Pro ASP.NET

clock July 3, 2015 06:07 by author Dan

If you got one of the following errors during WebMail Pro ASP.NET installation:

Creating/deleting folders Error, can't create folders in the data folder.
Creating/deleting files Error, can't create files in the data folder.
Error, can't read/write "C:\Inetpub\wwwroot\WebMailPro\App_Data\settings\*.xml" file.

This means WebMail Pro ASP.NET doesn't have permissions enough to read/write contents of App_Data subfolder.

Note: In this article, we assume your WebMail Pro ASP.NET is deployed to C:\Inetpub\wwwroot\WebMailPro\ folder, but if you've deployed it to another folder, you should take this into account when looking at the paths here.

To resolve the issue, you should grant Full Control permission to ASPNET, NETWORK SERVICE and Internet Guest Account system accounts over App_Data folder:

1. In Windows Explorer, go to C:\Inetpub\wwwroot\WebMailPro\ folder, right-click App_Data folder and choose Properties:

2. In General tab, make sure "Read-only" option is not set:

3. In Security tab, gran "Full Control" permission to ASPNET, NETWORK SERVICE and Internet Guest Account accounts:

4. Click OK. Now, WebMail Pro ASP.NET should have enough permissions to read/write files and folders in the App_Data folder.

Note: If you're installing WebMail Pro ASP.NET to a shared hosting, you'll be unable to assign permissions on your server via Windows Explorer as shown at the screenshots above. However, the control panel provided by your hosting should allow you to do the same. Please refer to your control panel documentation to learn how to do that or ask your hosting provider to assign the permissions for you.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET MVC hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Fix ASP.NET Menu Control Cannot Work in Google Chrome

clock May 22, 2015 06:16 by author Dan

Problem

If your website is using ASP.NET Menu Control, the menu part will not work in Google Chrome browser and Apple Safari browser. The look and feel of the main menu is different. Submenu does not show up.

Solution

There is an easy fix for this problem. Just copy and paste the following codes to your page load event of your code behind master page file. You may need to copy it to every page if you do not use master page.

     Partial Class Main
        Inherits System.Web.UI.MasterPage

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Request.UserAgent.IndexOf("AppleWebKit") > 0 Then
                Request.Browser.Adapters.Clear()
            End If
        End Sub
    End Class

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



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