@manhnguyenv

Welcome to my blog!

Authorize Attribute in ASP.NET MVC

November 4, 2019 10:12

Authorize Attribute in ASP.NET MVC (edit)

Helper:

        public class ApplicationAuthorizeAttribute : AuthorizeAttribute
	{
		protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
		{
			var httpContext = filterContext.HttpContext;
			var request = httpContext.Request;
			var response = httpContext.Response;
			var user = httpContext.User;

			if (request.IsAjaxRequest())
			{
				if (user.Identity.IsAuthenticated == false)
					response.StatusCode = (int)HttpStatusCode.Unauthorized;
				else
					response.StatusCode = (int)HttpStatusCode.Forbidden;

				response.SuppressFormsAuthenticationRedirect = true;
				response.End();
			}

			base.HandleUnauthorizedRequest(filterContext);
		}
	}

Controller:

		[HttpPost]
		public ActionResult GetData1()
		{
                    return Json(new
                    {
                        Items = new[] { "String 1", "String 2", "String 3" }
                    });
                }

		[HttpPost]
		[ApplicationAuthorize]
		public ActionResult GetData2()
		{
			return Json(new
			{
				Items = new[] { "String 1", "String 2", "String 3" }
			});
		}

		[HttpPost]
		[ApplicationAuthorize(Roles = "admin")]
		public ActionResult GetData3()
		{
                    return Json(new
                    {
                        Items = new[] { "String 1", "String 2", "String 3" }
                    });
                }

ASP.NET MVC: Using JavaScript with Ajax and Razor view

October 8, 2019 19:41

ASP.NET MVC: Using JavaScript with Ajax and Razor view

https://bitoftech.net/

View

<button id="btnGetData" type="button" class="btn btn-primary"> @Resources.GetData</button>

Controller

The complete list of objects is (they all receive the ControllerContext as the contructor parameter):

  • FormValueProvider: search for data in the body (Request.Form)
  • RouteDataValueProvider: search for data in the route (RouteData.Value)
  • QueryStringValueProvider: search for data in the query string (Request.QueryString)
  • HttpFileCollectionValueProvider: search for uploaded files (Request.Files)

System.Web.Mvc.HttpPostAttribute & System.Web.Http.HttpPostAttribute

  • System.Web.Mvc.HttpPostAttribute
  • System.Web.Http.HttpPostAttribute

IHttpActionResult & HttpResponseMessage

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results

https://www.infoworld.com/article/3192176/my-two-cents-on-using-the-ihttpactionresult-interface-in-webapi.html

ihttpactionresult

[FromBody]

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api#using-frombody

FromBodyAttribute Class (System.Web.Http)

// POST /api/Product/Post
[HttpPost]
public HttpResponseMessage Post([FromBody] Product product)
{
var name = product.Name; // "Product Name"
var price = product.Price; // 0.50
}

Model Binding

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

You can use one of the following attributes to specify the source to use for any given target:

Model

// a complex object
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}

JSON

{
  "Name" : "Product Name",
  "Price" : 0.50 
}

Action Get

// GET: /Home/GetData
[HttpGet]
public ActionResult GetData()
{
    try
    {
        string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
        string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
        string redirectUrl = Utilities.GetPageUrl(actionName, controllerName);
        string loginUrl = Utilities.GetLoginUrl();
        string loginUrlEncrypted = loginUrl;
        ViewBag.Url = loginUrl + redirectUrl;
        return Json(new { Success = true, Data = loginUrlEncrypted }, JsonRequestBehavior.AllowGet);
    }
    catch
    {
        return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
    }
}

Action Post

// POST: /Home/SaveData
[HttpPost]
public ActionResult SaveData([FromBody] Product product)
{
    try
    {
        string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
        string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
        bool success = Utilities.SaveProduct(product);
        return Json(new { Success = success, Message = "Success" }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { Success = false, Message = ex.ToString() }, JsonRequestBehavior.AllowGet);
    }
}

Call AJAX using JavaScript / jQuery

<script>
window.HomeSaveData = '@Url.Action("SaveData", "Home")';
$(function () {
var obj =
{
"Name" : "Product Name",
"Price" : 0.50
};
debugger;
$.ajax({
url: window.HomeSaveData,
type: "POST",
dataType: "json",
data: JSON.stringify(obj);
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
debugger;
if (resultData.Success = false) {
debugger;
} else {
var message = resultData.Message;
debugger;
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
timeout: 120000
});
});
</script>

Call AJAX using JavaScript / jQuery

<script>
window.HomeGetData = '@Url.Action("GetData", "Home")';
$(function () {
$.ajax({
url: window.HomeGetData,
type: "GET",
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
debugger;
if (resultData.Success = false) {
debugger;
} else {
var data = resultData.Data;
debugger;
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
timeout: 120000
});
});
</script>

Một số kinh nghiệm phát triển một Web App sử dụng ASP.NET MVC

May 31, 2019 09:26

Một số kinh nghiệm phát triển một Web App sử dụng ASP.NET MVC (edit)

+ Check null trước khi sử dụng .Name, .Age

+ Check null trước khi sử dụng .ToString(), .Parse()...

+ Khở tạo list rỗng trong constructor để tránh trường hợp sử dụng list đó khi mà list null

+ Không sử dụng return default value khi xảy ra Exception

+ Không sử dụng Cache cho những dữ liệu người dùng (private info, User Settings, ...)

+ Chú ý khi trả về từ lệnh return Json(..., );

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property

https://blogs.msdn.microsoft.com/mayurpatankar/2018/04/05/error-during-serialization-or-deserialization-using-the-json-javascriptserializer-the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-property/

Solution

https://stackoverflow.com/questions/47257227/the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-property-c

https://stackoverflow.com/questions/16848289/error-the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-proper

ASP.NET MVC Architecture

https://www.tutorialsteacher.com/mvc/mvc-architecture

https://www.c-sharpcorner.com/article/standard-application-architecture-in-mvc/

https://www.danylkoweb.com/Blog/top-10-books-every-net-developer-should-own-QG?quora

https://www.c-sharpcorner.com/article/mvc-5-demo-project-with-entity-framework-db-first/

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/database-first-development/setting-up-database

https://blog.trigent.com/caching-in-asp-net

https://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En

https://stackoverflow.com/questions/10515623/architectural-decisions-asp-net-mvc-entity-framework

https://stackoverflow.com/questions/15856660/architecture-for-aspnet-mvc-web-application

TDD with MVC Applications

July 30, 2018 23:08

TDD with MVC Applications (edit)

TDD With MVC 5 and Entity Framework and Repository pattern

https://code.msdn.microsoft.com/TDD-With-MVC-5-and-Entity-83ade5cf

Developing an ASP.NET MVC 4 Application for TDD using xUnit and Moq

https://github.com/dotnetcurry/tddusingxunit-dncmag-01

ASP.NET MVC 5 application with TDD using Unit testing framework (xUnit.NET) and Moking/Isolation framework (MOQ)

https://github.com/SanjeevForYou/TDDWithxUnitAndMOQ

TDD in ASP.NET MVC Applications with Moq Framework

https://kakimotonline.com/2011/02/13/tdd-in-asp-net-mvc-applications-with-moq-framework/

Unit Testing .NET Application with Moq Framework

https://kakimotonline.com/2011/01/02/unit-testing-net-application-with-moq-framework/

Test Driven Development in ASP.NET MVC 2

https://visualstudiomagazine.com/articles/2015/02/25/code-management-test-driven-dev.aspx

Test Driven Development in ASP.NET MVC 2

https://visualstudiomagazine.com/Articles/2015/05/14/Test-Driven-ASP-NET-MVC-2.aspx

TDD with .NET Core Web API

https://asp.net-hacker.rocks/2017/09/27/testing-aspnetcore.html

https://github.com/JuergenGutsch/blog/blob/master/_source/_posts/2017-09-27-testing-aspnetcore.md

 

 

ASP.NET MVC + Web API

May 21, 2018 17:54

ASP.NET MVC (edit)

https://github.com/chsakell/mvcarchitecture

ASP.NET Web API

https://github.com/chsakell/webapiunittesting

SPA + Web API

https://github.com/chsakell/spa-webapi-angularjs

ASP.NET MVC + AdminLTE

March 31, 2018 00:14

ASP.NET MVC + AdminLTE (edit)

ASP.NET MVC Application with a Custom Layout (Login screen)

https://code.msdn.microsoft.com/ASPNET-MVC-Application-b4b0dc3f

A NuGet package for integrating Admin LTE 2.0.4 into ASP.Net MVC 5

https://github.com/eralston/AdminLteMvc (AdminLTE version 2.0.4)

ASP.NET Example Version of Beautiful AdminLTE Template

https://github.com/go2ismail/AdminLTE-ASP-NET-MVC (AdminLTE version 2.4.0)

Tutorials & Samples on adding Charts into ASP.NET MVC Applications

https://canvasjs.com/docs/charts/integration/asp-net-mvc-charts/ (Chart)

CRUD Operations in ASP.NET MVC Using AJAX and Bootstrap

https://dzone.com/articles/crud-operation-in-aspnet-mvc-using-ajax-and-bootst

AdminLTE +  ASP.NET MVC 5 + Net Framework 4.8

https://github.com/DiomedesDominguez/AdminLTE.NET

ASP.NET MVC 5 Scaffolding

https://github.com/robinli/MVC5-Scaffolder

ASP.NET MVC 5 SmartCode Scaffolding (HAY HAY HAY)

https://github.com/neozhu/MVC5-Scaffolder

https://www.bbsmax.com/A/kvJ3LkNp5g/

http://www.matools.com/lang-en/blog/190137840

https://www.cnblogs.com/neozhu/p/8744414.html

https://blog.csdn.net/weixin_34235457/article/details/94016484

https://blog.csdn.net/sd7o95o/article/details/78519238

https://blog.csdn.net/weixin_34080951/article/details/94523127

ASP.NET MVC 5 Scaffolding

https://github.com/tzhsweet/MVC5-Scaffolder

ASP.NET Web API Attribute Routing

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing#controller-code

AdminLTE Template

https://github.com/weituotian/AdminLTE-With-Iframe (HAY HAY HAY)

https://github.com/tzhsweet/MVC5-Scaffolder (HAY HAY HAY) - Demo: http://longle.azurewebsites.net/

Demo: https://weituotian.oschina.io/adminlte-with-iframe/index2.html

Demo: https://weituotian.github.io/AdminLTE-With-Iframe/

Preview on github: https://weituotian.github.io/AdminLTE-With-Iframe/pages/index_iframe.html

Preview on oschina: http://weituotian.oschina.io/adminlte-with-iframe/pages/index_iframe.html

https://www.c-sharpcorner.com/article/dashboard-application-with-asp-net-mvc-5-and-jquery/ (HAY HAY HAY)

https://github.com/cyberzilla/dycms (HAY HAY HAY) - How can I implement Tab Pages in AdminLTE?

rrpuz7 x7rns4 9wly7m61z

https://www.quora.com/Where-can-I-find-free-ASP-NET-dashboard-templates (Where can I find free ASP.NET Dashboard templates?)

https://marketplace.visualstudio.com/items?itemName=c0shea.AdminLTETemplate (AdminLTE version 2.4.9)

https://marketplace.visualstudio.com/items?itemName=DiomedesIgnacioDominguezUrena.N-LayerAdminLTENET (AdminLTE version 2.4.9)

https://awesomeopensource.com/projects/adminlte (AdminLTE version 2.4.9)

http://hjnilsson.github.io/country-flags/ (Country flags)

https://vimeo.com/125426951 (IdentityManager with ASP.NET Identity)

https://github.com/eralston/AdminLteMvc/ (AdminLTE version 2.0.4)

https://www.youtube.com/watch?v=xnncfeFv108 (AdminLTE in ASP.NET Core MVC)

Good resources

https://www.jerriepelser.com/blog/5-weeks-of-aspnet-weekly-tools-and-libraries-part-1/

https://www.jerriepelser.com/blog/5-weeks-of-aspnet-weekly-tools-and-libraries-part-2/

https://www.jerriepelser.com/blog/5-weeks-of-aspnet-weekly-tools-and-libraries-part-3/

AdminLTE Downloads

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.10.zip

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.9.zip

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.5.zip

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.0.zip (HAY)

AdminLTE Guide

https://adminlte.io/themes/AdminLTE/documentation/index.html

https://www.howtosolutions.net/2017/05/visual-studio-asp-net-mvc-project-installing-adminlte-control-panel/ (HAY)

AdminLTE + MVC 5
https://github.com/go2ismail/AdminLTE-ASP-NET-MVC
https://github.com/c0shea/AdminLTE-Template (HAY)
https://code.msdn.microsoft.com/ASPNET-MVC-Application-b4b0dc3f/
https://github.com/Magik3a/Multi-Language-API

Patient Management
https://github.com/Magik3a/PatientManagement_Admin

Design and Print Stickers

https://github.com/Magik3a/DesignAndPrintStickers
jQuery file upload, iTextSharp, Html Agility Pack, Cropper v2.3.3 - jQuery image cropping plugin

Easy Admin Dashboard with MVC
http://prabathsl.blogspot.com/2016/04/easy-admin-dashboard-with-mvc.html

Admin Dashboard
https://www.nuget.org/packages/Admin_Dashboard/
Install-Package Admin_Dashboard -Version 1.0.0

AdminLTE
https://github.com/almasaeed2010/AdminLTE

CMS MVC5
+ AdminLteMvc (https://github.com/eralston/AdminLteMvc)
+ Mvc CMS (https://github.com/jwmcpeak/Building-a-CMS-With-ASP.NET-MVC5)
+ Mr CMS (https://github.com/MrCMS/MrCMS)
+ MVCwCMS (https://github.com/valgen/mvcwcms)
+ Umbraco (https://github.com/umbraco/Umbraco-CMS)
+ sBlog.Net (https://github.com/karthik25/sblog.net)
+ N2CMS (https://github.com/n2cms/n2cms)
+ Better CMS
+ Piranha CMS (https://github.com/PiranhaCMS/Piranha)
+ BlogEngine.NET (https://github.com/rxtur/BlogEngine.NET)
+ Awesome (https://github.com/quozd/awesome-dotnet)

CMS MVC6
+ AdminLte .NET Core (https://github.com/moemura/AdminLTE.Core)
+ Awesome .NET Core (https://github.com/thangchung/awesome-dotnet-core)

Ecommerce MVC5
+ NopCommerce (https://github.com/nopSolutions/nopCommerce)

Ecommerce MVC6
+ SimplCommerce (https://github.com/simplcommerce/simplcommerce)

Scheduler
+ Quartznet (https://github.com/quartznet/quartznet)
+ FluentScheduler (https://github.com/fluentscheduler/FluentScheduler)
+ Hangfire (https://www.hangfire.io/)

Search
+ ElasticSearch (https://github.com/elastic/elasticsearch-net)

Templates
+ Boilerplate (https://github.com/ASP-NET-Core-Boilerplate/Templates)
+ MVC Bootstrap (https://github.com/steve-haar/MVC-Bootstrap)

MVC

December 3, 2017 21:48

Best Practices (edit)

https://stackoverflow.com/questions/32641858/what-is-the-best-practice-for-enterprise-level-application-architecture-using-mv

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

https://code.msdn.microsoft.com/NET-best-practice-samples-4e9b92a4

 

I would start with PCI-DSS guidance as a baseline for protecting the data.

PCI-DSS is the Payment Card Industry Data Security Standard. It's the industries first attempt to lay down guidelines for protecting data around the banking area. The guidelines are specifically for cardholder data, but are a great resource for protection of data in general. PCI requirements include yearly onsite audits, and quarterly network scans.

Another good resource is OWASP which offers guidance on security of web applications in general

OWASP goes into a lot of detail about how to perform threat modelling, test for (and correct) common vulnerabilities. For the quick start head to the OWASP Top Ten

 

AllowHtml, DataAnnotation

https://www.c-sharpcorner.com/article/best-practices-for-asp-net-mvc-application/

Overview MVC 1,2,3,4,5 + @section scripts

https://www.c-sharpcorner.com/article/best-practice-for-mvc/

MVC Solution Architecture (source)

https://chsakell.com/2015/02/15/asp-net-mvc-solution-architecture-best-practices/

Action Filter

https://www.danylkoweb.com/Blog/my-top-5-aspnet-mvc-actionfilters-AD

Unobtrusive Validation

https://stackoverflow.com/questions/14902581/unobtrusive-validation-not-working-with-dynamic-content/

https://stackoverflow.com/questions/28090143/best-practices-viewmodel-validation-in-asp-net-mvc

Data Annotation: Đa ngôn ngữ với Model Metadata

https://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx/

Good Practices

http://www.codemag.com/article/1405071/10-Good-Practices-for-ASP.NET-MVC-Apps

https://www.codeguru.com/csharp/.net/net_asp/mvc/top-10-asp.net-mvc-best-practices.htm

Nerd Dinner

http://nerddinner.codeplex.com/

MVC Music Store

MVC Music Store is a tutorial application built on ASP.NET MVC. It's a lightweight sample store which demonstrates ASP.NET MVC using Entity Framework.

How to run MVC Music Store?

1) Download and install ASP.NET MVC 3 Tools from the official ASP.NET MVC 3 page or from Microsoft Download Center. It will install the required DLLS into the GAC.

2) Install the corresponding ASP.NET MVC 3 NuGet package into MvcMusicStore project using following command in the Package Manager Console:

Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1

or

Install-Package Microsoft.AspNet.Mvc -Version 3.0.20105.1

After using either of the described ways you will be able to successfully build and run the MVC Music Store tutorial application.

Note that these ways are not conflicting with each other, so you may safely install ASP.NET MVC 3 Tools into your OS and install ASP.NET MVC 3 NuGet package into the project.

C#

https://stackify.com/net-core-csharp-next-programming-language/

https://stackify.com/learn-c-sharp-tutorials/

MVC

https://www.danylkoweb.com/Blog/what-is-the-best-and-fastest-way-to-learn-aspnet-mvc-8V

https://weblogs.asp.net/jongalloway/learn-asp-net-mvc-3-with-the-mvc-music-store-tutorial 

https://mvcmusicstore.codeplex.com/

https://github.com/aspnet/MusicStore

https://github.com/nffish/MvcMusicStore

https://github.com/evilDave/MVC-Music-Store

Learn MVC in CodeProject

https://www.codeproject.com/Articles/866143/Learn-MVC-Project-in-days-Day

 

Categories

Recent posts