Maximum request length exceeded

Lỗi: 

Maximum request length exceeded 

Nguyên nhân:

ASP.NET web server cấu hình mặc định cho phép upload tối đa 4096 KB (4MB), khi upload quá kích thức thì xảy ra lỗi trên

Khắc phục:

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

Hoặc nếu là IIS lớn hơn phiên bản 7.0

<system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Lỗi khi đưa lên host của nhà cung câp – Unrecognized attribute ‘targetFramework’

Khi đưa lên host của nhà cung cấp, với lỗi thường gặp sau

Unrecognized attribute ‘targetFramework’. Note that attribute names are case-sensitive.

Nguyên nhân và cách khắc phục

  • Nguyên nhân

Website đang được thiết lập cấu hình mặc định là AppPool ASP.NET 2.0

  • Khắc phục

Chuyển AppPool qua ASP.NET 4.0

Razor syntax

Syntax/Sample Razor Web Forms Equivalent (or remarks)
Code Block
@{ 
  int x = 123; 
  string y = "because.";
}
<%
  int x = 123; 
  string y = "because."; 
%>
Expression (Html Encoded)
<span>@model.Message</span>
<span><%: model.Message %></span>
Expression (Unencoded)
<span>
@Html.Raw(model.Message)
</span>
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
  <span>@item.Prop</span> 
}
<% foreach(var item in items) { %>
  <span><%: item.Prop %></span>
<% } %>
Mixing code and Plain text
@if (foo) {
  <text>Plain Text</text> 
}
<% if (foo) { %> 
  Plain Text 
<% } %>
Using block
@using (Html.BeginForm()) {
  <input type="text" value="input here">
}
<% using (Html.BeginForm()) { %>
  <input type="text" value="input here">
<% } %>
Mixing code and plain text (alternate)
@if (foo) {
  @:Plain Text is @bar
}
Same as above
Email Addresses
Hi philha@example.com
Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Explicit Expression
<span>ISBN@(isbnNumber)</span>
In this case, we need to be explicit about the expression by using parentheses.
Escaping the @ sign
<span>In Razor, you use the 
@@foo to display the value 
of foo</span>
@@ renders a single @ in the response.
Server side Comment
@*
This is a server side 
multiline comment 
*@
<%--
This is a server side 
multiline comment
--%>
Calling generic method
@(MyClass.MyMethod<AType>())
Use parentheses to be explicit about what the expression is.
Creating a Razor Delegate
@{
  Func<dynamic, object> b = 
   @<strong>@item</strong>;
}
@b("Bold this")
Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details.
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.

Source: haacked.com

Error: The OwinStartup attribute discovered in assembly

Khi gặp lỗi sau:

The OwinStartup attribute discovered in assembly ‘eNoteBookApp’ referencing startup type ‘eNoteBookApp.Startup’ conflicts with the attribute in assembly ‘eHandbook’ referencing startup type ‘eHandbook.Startup’ because they have the same FriendlyName ”. Remove or rename one of the attributes, or reference the desired type directly.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of “false” in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config

Hãy xử lý bằng cách:

Mở web.config và bổ sung key sau vào appSettings

<appSettings>
<add key=“owin:AutomaticAppStartup” value=“false”/>
</appSettings>

Shopping cart demo

Mã nguồn đính kèm là ví dụ về cách xây dựng Shopping cart trong ASP.NET MVC, bạn có thể tải mã nguồn đầy đủ ở link sau.

Ví dụ sử dụng csdl Northwind có thể download về từ site của Microsoft.

Code tham khảo ở HomeController.cs

public ActionResult Index()
{
Models.Northwind2Entities db = new Models.Northwind2Entities();
return View(db.Products.ToList());
}
public ActionResult AddToCart(int id, int quantity =1)
{
ShoppingCart cart = (ShoppingCart)Session[“cart”];
if (cart == null){
cart = new ShoppingCart();
}
cart.AddItem(id.ToString(), quantity, 300);
//Save cart
Session[“cart”] = cart;
return RedirectToAction(“YourCart”);
}
public ActionResult YourCart()
{
return View();
}
public ActionResult RemoveItem(int id)
{
ShoppingCart cart = (ShoppingCart)Session[“cart”];
if (cart == null){
cart = new ShoppingCart();
}
cart.RemoveItem(id.ToString());
return RedirectToAction(“YourCart”);
}

public ActionResult Checkout()
{
ShoppingCart cart = HttpContext.Session[“cart”] as ShoppingCart;
//Process your cart

//remove cart
HttpContext.Session.Clear();
return RedirectToAction(“Index”);
}

Code trong Home/Index view

 

idx

Home/Yourcart view

yc

ShoppingCart.cs class

public class ShoppingCart
 {
 // internal member variables
 private String user;
 private DataTable items;
 private Double total;

 // public properties
 public String UserID
 {
 get { return user; }
 set { user = value; }
 }
 public DataTable CartItems
 {
 get { return items; }
 set { items = value; }
 }
 public Double TotalValue
 {
 get { return total; }
 set { total = value; }
 }
 // default constructor
 public ShoppingCart()
 {
 // create an empty shopping cart
 user = String.Empty;
 // create an empty DataTable to hold the cart items
 items = new DataTable("Items");
 items.Columns.Add(new DataColumn("ProductID", Type.GetType("System.String")));
 items.Columns.Add(new DataColumn("Quantity", Type.GetType("System.Int32")));
 items.Columns.Add(new DataColumn("Price", Type.GetType("System.Double")));
 // set total value of the new cart to zero 
 total = 0;
 }
 public void UpdateCart()
 {
 //Update cart code
 }
 public void RemoveItem(string productID)
 {
 DataRow[] rows = items.Select("ProductID='" + productID + "'");
 if (rows.Length > 0)
 {
 items.Rows.Remove(rows[0]);
 }
 }
 // add an item to the cart
 public void AddItem(String proId, Int32 Qty, Double price)
 {
 if (!IsExistItem(proId))
 {
 // create new DataTable row and populate with values - Hàng mới
 DataRow row = items.NewRow();
 row["ProductID"] = proId;
 row["Quantity"] = Qty;
 row["Price"] = price;
 // add row to DataTable update total value
 items.Rows.Add(row);
 total += (Qty * price);
 }
 else
 {
 //tăng số lượng hàng trong giỏ hàng
 for (int i = 0; i < items.Rows.Count; i++)  {  if (items.Rows[i]["ProductID"].Equals(proId))  {  items.Rows[i]["Quantity"] = int.Parse(items.Rows[i]["Quantity"].ToString()) + Qty;  total += (Qty * price);  break;//Exit loop  }  }  }  }  public bool IsExistItem(string proID)  {  bool b = false;  if (items.Rows.Count > 0)
 {
 for (int i = 0; i < items.Rows.Count; i++)
 {
 if (items.Rows[i]["ProductID"].Equals(proID))
 {
 b = true;
 break;//exit loop
 }
 }
 }
 return b;
 }
 // empty the cart by clearing the DataTable
 public void Clear()
 {
 items.Rows.Clear();
 total = 0;
 }
 }

Bài 11 – Enforcing SSL in an ASP.NET Core app

Thiết lập: Require SSL

  • Bổ sung dòng mã dưới đây vào phương thức ConfigureServices trong lớpStartup.cs:
// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});

}

  • Bổ sung đoạn mã sau vào phương thức Configure(…)

15

Lưu ý: phải cài gói sau trước khi sử dụng RewriteOptions()

Install-Package Microsoft.AspNetCore.Rewrite

Set up IIS Express for SSL/HTTPS

  • Trong cửa sổ Solution Explorer, click chuột phải trên Project và chọn Properties.
  • Trên pane bên trái, chọn Debug
  • Check Enable SSL
  • Copy đường dẫn SSL và dán vào ô text App URL

Bài 10 – using tag helpers in forms in ASP.NET Core

The Form Tag Helper

10

The Input Tag Helper

<input asp-for=“<Expression Name>” />

12

Expression names

13

The Textarea Tag Helper

14

The Label Tag Helper

<label asp-for=“Email”></label>

The Validation Tag Helpers

<span asp-validation-for=“Email”></span>

The Validation Summary Tag Helper

<div asp-validation-summary=“ModelOnly”></div>

The Select Tag Helper

<select asp-for=“Country” asp-items=“Model.Countries”></select>