當前位置:首頁 » 網頁前端 » ASPNETWebAPI設計pdf
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

ASPNETWebAPI設計pdf

發布時間: 2022-04-21 02:16:44

A. asp.net mvc3 項目怎麼開發API介面

Visual Studio為我們提供了專門用於創建ASP.NET Web API應用的項目模板,藉助於此項目模板提供的向導,我們可以「一鍵式」創建一個完整的ASP.NET Web API項目。在項目創建過程中,Visual Studio會自動為我們添加必要的程序集引用和配置,甚至會為我們自動生成相關的代碼,總之一句話:這種通過向導生成的項目在被創建之後其本身就是一個可執行的應用。

對於IDE提供的這種旨在提高生產效率的自動化機制,我個人自然是推崇的,但是我更推薦讀者朋友們去了解一下這些自動化機制具體為我們做了什麼?做這些的目的何在?哪些是必需的,哪些又是不必要的?正是基於這樣的目的,在接下來演示的實例中,我們將摒棄Visual Studio為我們提供的向導,完全在創建的空項目中編寫我們的程序。這些空項目體現在如右圖所示的解決方案結構中。
如右圖所示,整個解決方案一共包含6個項目,上面介紹的作為「聯系人管理器」的單頁Web應用對應著項目WebApp,下面的列表給出了包括它在內的所有項目的類型和扮演的角色。
·Common:這是一個空的類庫項目,僅僅定義了表示聯系人的數據類型而已。之所以將數據類型定義在獨立的項目中,只要是考慮到它會被多個項目(WebApi和ConsoleApp)所使用。
WebApi:這是一個空的類庫項目,表現為HttpController類型的Web API就定義在此項目中,它具有對Common的項目引用。
WebHost:這是一個空的ASP.NET Web應用,它實現了針對ASP.NET Web API的Web Host寄宿,該項目具有針對WebApi的項目引用。
SelfHost:這是一個空的控制台應用,旨在模擬ASP.NET Web API的Self Host寄宿模式,它同樣具有針對WebApi的項目引用。
WebApp:這是一個空的ASP.NET Web應用,代表「聯系人管理器」的網頁就存在於該項目之中,至於具體的聯系人管理功能,自然通過以Ajax的形式調用Web API來完成。
ConsoleApp:這是一個空的控制台應用,我們用它來模擬如何利用客戶端代理來實現對Web API的遠程調用,它具有針對Common的項目引用。
二、定義Web API
在正式定義Web API之前,我們需要在項目Common中定義代表聯系人的數據類型Contact。簡單起見,我們僅僅為Contact定義了如下幾個簡單的屬性,它們分別代表聯系人的ID、姓名、聯系電話、電子郵箱和聯系地址。
1: public class Contact
2: {
3: public string Id { get; set; }
4: public string Name { get; set; }
5: public string PhoneNo { get; set; }
6: public string EmailAddress { get; set; }
7: public string Address { get; set; }
8: }

表現為HttpController的Web API定義在WebApi項目之中,我們一般將ApiController作為繼承的基類。ApiController定義在「System.Web.Http.dll」程序集中,我們可以在目錄「%ProgramFiles%\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages\」中找到這個程序集。具體來說,該程序集存在於子目錄「Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45」中。
Web API體現在如下所示的ContactsController類型中。在該類型中,我們定義了Get、Post、Put和Delete這4個Action方法,它們分別實現了針對聯系人的查詢、添加、修改和刪除操作。Action方法Get具有一個表示聯系人ID的可預設參數,如果該參數存在則返回對應的聯系人,否則返回整個聯系人列表。由於ASP.NET Web API默認實現了Action方法與HTTP方法的映射,所以方法名也體現了它們各自所能處理請求必須採用的HTTP方法。
1: public class ContactsController: ApiController
2: {
3: static List<Contact> contacts;
4: static int counter = 2;
5:
6: static ContactsController()
7: {
8: contacts = new List<Contact>();
9: contacts.Add(new Contact { Id = "001", Name = "張三",
10: PhoneNo = "0512-12345678", EmailAddress = "[email protected]",
11: Address = "江蘇省蘇州市星湖街328號" });
12: contacts.Add(new Contact { Id = "002", Name = "李四",
13: PhoneNo = "0512-23456789", EmailAddress = "[email protected]",
14: Address = "江蘇省蘇州市金雞湖大道328號" });
15: }
16:
17: public IEnumerable<Contact> Get(string id = null)
18: {
19: return from contact in contacts
20: where contact.Id == id || string.IsNullOrEmpty(id)
21: select contact;
22: }
23:
24: public void Post(Contact contact)
25: {
26: Interlocked.Increment(ref counter);
27: contact.Id = counter.ToString("D3");
28: contacts.Add(contact);
29: }
30:
31: public void Put(Contact contact)
32: {
33: contacts.Remove(contacts.First(c => c.Id == contact.Id));
34: contacts.Add(contact);
35: }
36:
37: public void Delete(string id)
38: {
39: contacts.Remove(contacts.First(c => c.Id == id));
40: }
41: }

簡單起見,我們利用一個靜態欄位(contacts)表示存儲的聯系人列表。當ContactsController類型被載入的時候,我們添加了兩個ID分別為「001」和「002」的聯系人記錄。至於實現聯系人CRUD操作的Action方法,我們也省略了必要的驗證,對於本書後續的演示的實例,我們基本上也會採用這種「簡寫」的風格。

B. 《Web程序設計ASP.NET第2版》pdf下載在線閱讀全文,求百度網盤雲資源

《Web程序設計ASP.NET第2版》網路網盤pdf最新全集下載:
鏈接:https://pan..com/s/1ayPcM5FHJG2RHV5BhMjm2w

?pwd=oq5i 提取碼:oq5i
簡介:全書共12章,內容分為兩部分。第一部分為第1章和第2章,主要介紹Web基礎知識和ASPNET相關知識。第二部分為第3章-第12章,從網路涉及的實用模塊出發,結合流行的技術和組件,詳細介紹每個模塊的設計原理及實現過程,進而講解ASP.NET在網路開發中的應用,內容主要包括ASPNET控制項、ADO.NET、數據綁定、LINQ查詢、網站主題、數據驗證和網路優化等。

本書實踐知識與理論知識並重,力求使讀者通過親自動手來掌握ASPNET新技術,從而學習盡可能多的知識,了解盡可能多的應用。本書可作為普通高等院校相關專業Web程序設計、網路程序設計、ASPNET程序設計等課程的教材,同時也適用於初、中級ASPNET用戶學習參考。

C. 如何在Windows Server2008R2中部署WebAPI

一、安裝說明:
1、安裝基本信息
電腦軟體
在WindowsServer2008(或WindowsServer2008R2)中,單擊「開始」-「程序」-「管理工具」-「伺服器管理」,或在「運行」中輸入命令:servermanager.msc命令打「伺服器管理」程序。
在「角色」選項中,單擊「添加角色」:
選擇伺服器角色:Web伺服器(IIS)
單擊選中「web伺服器(IIS))前面的單選框。
在彈出的對話框中,單擊「添加必需的功能」:

「添加角色向導」對web伺服器進行簡單介紹,之後單擊「下一步」:
選擇角色需要的相關服務之後單擊「下一步」:
確認安裝選擇,之後單擊「下一步」:
系統開始安裝所選的角色服務,可能需要幾十秒可幾鍾時間:
安裝完成,點擊關閉即可:

名稱:IIS7.0安裝
大小:10MB|版本:7.0|類別:系統工具|語言:中文
應用平台:windows server 2008
2、安裝介紹
windows server 2008系統中的iis安裝,與windows server 2003中的安裝明顯不再相同了,windows server 2008安裝iis,不再需要其他相關組件,不像windows server 2003需要有i386文件,下面來詳細介紹一下,windows server 2008安裝iis的步驟:
二、安裝步驟:
開始--伺服器管理--角色--添加角色

點擊添加必需的功能

勾選在「Web伺服器(IIS)」

點擊下一步

下面是選擇「角色服務」的,針對你需要的進行相應的選擇

然後點擊「下一步」開始確認安裝

然後等待安裝成功

D. 如何使用 Web API 來對 MVC 應用程序進行身份驗證

首先,讓我們先更新 API 項目

我們將先對 API 項目進行必要的修改,修改完成之後再切換到 Web 項目對客戶端進行更新。

第1步:我們需要一個資料庫

在能做任何操作之前我們需要先創建一個資料庫。本例中將使用 SQL Server Express。如果你沒有安裝,可以從這里下載 SQL Server Express。安裝完成之後,創建一個名為 CallingWebApiFromMvc 的資料庫。這就是第一步要做的。

Api 項目還需要一個資料庫連接字元串,否則我們寸步難行。把下面這段代碼插入到 Api 項目的Web.config 文件中:

<connectionStrings>
<add name="ApiFromMvcConnection" connectionString="Data Source=(local);Initial Catalog=CallingWebApiFromMvc;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings>

認證(Identity)框架會自動創建我們管理用戶所需要的成員關系表,現在不需要擔心去提前創建它們。

第2步:添加相關的Nuget包

接下來我們添加用於OWIN和Windows認證的Nuget包。打開包管理控制台,切換Api項目為預設項目,輸入以下命令:

Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.AspNet.Identity.Owin

使用這些包可以在我們的應用中啟動一個OWIN伺服器,然後通過EntityFramework把我們的用戶保存到SQL Server。

第3步:添加管理用戶的Identity類

我們使用基於Windows認證機制之上的Entity框架來管理資料庫相關的業務。首先我們需要添加一些用於處理的類。在Api項目里添加一個Identity目錄作為我們要添加類的命名空間。然後添加如下的類:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{ public ApplicationDbContext() : base("ApiFromMvcConnection") {}
public static ApplicationDbContext Create()
{ return new ApplicationDbContext();
}
}

注意我們傳給基類構造函數的參數ApiFromMvcConnection要和Web.config中的連接字元串中的name相匹配。

public class ApplicationUserManager : UserManager<ApplicationUser>
{ public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
{
} public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{ var manager = new ApplicationUserManager(new UserStore<ApplicationUser> (context.Get<ApplicationDbContext> ()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser> (manager)
{
= false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
}; var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser> (dataProtectionProvider.Create("ASP.NET Identity"));
} return manager;
}
}

第4步:添加OWIN啟動類

為了讓我們的應用程序作為OWIN伺服器上運行,我們需要在應用程序啟動時初始化。我們可以通過一個啟動類做到這一點。我們將裝點這個類的
OwinStartup屬性,因此在應用程序啟動時觸發。這也意味著,我們可以擺脫的Global.asax和移動它們的
Application_Start代碼轉換成我們新的啟動類。

using Microsoft.Owin;

[assembly: OwinStartup(typeof(Levelnis.Learning.CallingWebApiFromMvc.Api.Startup))]
namespace Levelnis.Learning.CallingWebApiFromMvc.Api
{
using System;
using System.Web.Http;
using Identity;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Providers;
public class Startup
{ public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager> (ApplicationUserManager.Create); var oAuthOptions = new
{
TokenEndpointPath = new PathString("/api/token"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(oAuthOptions);
}
}
}

在應用程序啟動時,我們正在建立自己的伺服器。在這里,我們配置令牌端點並設置自己的自定義提供商,我們用我們的用戶進行身份驗證。在我們的例子中,我們使用了ApplicationOAuthProvider類。讓我們來看看現在:

第5步:添加OAuth的提供商

public class ApplicationOAuthProvider :
{ public override Task ValidateClientAuthentication( context)
{
context.Validated();
return Task.FromResult<object> (null);
}
public override async Task GrantResourceOwnerCredentials( context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager> ();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect."); return;
}
var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); var cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); var properties = CreateProperties(user.UserName); var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
private static AuthenticationProperties CreateProperties(string userName)
{
var data = new Dictionary<string, string>
{
{
"userName", userName
}
};
return new AuthenticationProperties(data);
}
}

我們感興趣的是這里2種方法。第一,ValidateClientAuthentication,只是驗證客戶端。我們有一個客戶端,所以返回成
功。這是一個非同步方法簽名但沒有非同步調用發生。正因為如此,我們可以離開了非同步修改,但我們必須返回一個任務自己。我們增加了一個名為
GenerateUserIdentityAsync的ApplicationUser,它看起來像這樣的方法:

public class ApplicationUser : IdentityUser
{ public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
return userIdentity;
}
}

第6步:注冊一個新用戶 - API端
所以,我們有到位的所有Identity類管理用戶。讓我們來看看RegisterController,將新用戶保存到我們的資料庫。它接受一個RegisterApi模式,這是簡單的:

public class RegisterApiModel
{
[Required]
[EmailAddress] public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password {
get; set;
}

[Required]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

控制器本身,如果注冊成功只是返回一個200 OK響應。如果驗證失敗,則返回401錯誤請求的響應。

public class RegisterController : ApiController
{ private ApplicationUserManager UserManager
{ get
{ return Request.GetOwinContext().GetUserManager<ApplicationUserManager> ();
}
} public IHttpActionResult Post(RegisterApiModel model)
{ if (!ModelState.IsValid)
{ return BadRequest(ModelState);
} var user = new ApplicationUser
{
Email = model.Email,
UserName = model.Email,
EmailConfirmed = true
};
var result = UserManager.Create(user, model.Password);
return result.Succeeded ? Ok() : GetErrorResult(result);
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (result.Errors != null)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
}

E. 如何在WPF應用程序中通過HttpClient調用Web API

Asynchronous Calls
非同步調用

HttpClient is designed to be non-blocking. Potentially long-running operations are implemented as asynchonrous methods, such as GetAsync and PostAsync. These methods return without waiting for the operation to complete. The previous tutorial (Calling a Web API From a Console Application) showed only blocking calls:
HttpClient被設計成是非阻塞的。潛在地,長時間運行的操作是作為非同步方法實現的,例如,GetAsync和PostAsync。這些方法不會等待操作完成便會返回。上一教程(通過控制台應用程序調用Web API)只展示了阻塞調用:

HttpResponseMessage response = client.GetAsync("api/procts").Result; // Blocking call(阻塞)!
This code blocks the calling thread by taking the Result property. That's OK for a console application, but you should not do it from a UI thread, because it blocks the UI from responding to user input.
這段代碼通過採用Result屬性,會阻塞調用線程。對於一個控制台應用程序,這沒問題,但你不應該在一個UI線程中採用這一做法,因為這會阻止UI去響應用戶輸入。

The asynchronous methods of HttpClient return Task objects that represent the asynchronous operation.
HttpClient的非同步方法會返回表示非同步操作的Task對象。

Create the WPF Project
創建WPF項目

Start Visual Studio. From the Start menu, select New Project. In the Templates pane, select Installed Templates and expand the Visual C# node. In the list of project templates, select WPF Application. Name the project and click OK.
啟動Visual Studio。從「開始」菜單選擇「新項目」。在「模板」面板中,選擇「已安裝模板」,並展開「Viusal C#」節點。在項目模板列表中,選擇「WPF應用程序」。命名此項目並點擊「OK」。

Open MainWindow.xaml and add the following XAML markup inside the Grid control:
打開MainWindow.xaml,並在Grid控制項中添加以下XAML標記:

<StackPanel Width="250" >
<Button Name="btnGetProcts" Click="GetProcts">Get Procts</Button>
<ListBox Name="ProctsList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="2">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock >Price: $<Run Text="{Binding Path=Price}" />
(<Run Text="{Binding Path=Category}" />)</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
This markup defines a ListBox that will be data-bound to the list of procts. The DataTemplate defines how each proct will be displayed.
這段標記定義了一個將被數據綁定到產品列表的ListBox(列表框)。DataTemplate(數據模板)定義了如何顯示每個產品。(其效果如圖3-4所示)。


圖3-4. WPF界面效果

Add the Model Class
添加模型類

Add the following class to the application:
將以下類添加到應用程序:

class Proct
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
}
This class defines a data object that HttpClient will write into the HTTP request body and read from the HTTP response body.
這個類定義了一個數據對象,HttpClient將把它寫入HTTP請求體,也從HTTP響應體中讀取它。

We'll also add an observable class for data binding:
我們也要添加一個用於數據綁定的可見對象類(observable class):

class ProctsCollection : ObservableCollection<Proct>
{
public void CopyFrom(IEnumerable<Proct> procts)
{
this.Items.Clear();
foreach (var p in procts)
{
this.Items.Add(p);
}
this.OnCollectionChanged(
new (NotifyCollectionChangedAction.Reset));
}
}
Install NuGet Package Manager
安裝NuGet包管理器

NuGet Package Manager is the easiest way to add the Web API Client library to a project. If you do not have NuGet Package Manager already installed, install it as follows.
將Web API客戶端庫添加到項目最容易的辦法是安裝「NuGet包管理器(NuGet Package Manager)」。如果尚未安裝NuGet包管理器,按如下步驟安裝。
1.Start Visual Studio.
啟動Visual Studio.
2.From the Tools menu, select Extensions and Updates.
從「工具」菜單選擇「擴展與更新」
3.In the Extensions and Updates dialog, select Online.
在「擴展與更新」對話框中,選擇「在線」
4.If you don't see "NuGet Package Manager", type "nuget package manager" in the search box.
如果未看到「NuGet包管理器」,在搜索框中輸入「nuget package manager」。
5.Select the NuGet Package Manager and click Download.
選擇「NuGet包管理器」,並點擊「下載」。
6.After the download completes, you will be prompted to install.
下載完成後,會提示你安裝。
7.After the installation completes, you might be prompted to restart Visual Studio.
安裝完成後,可能會提示重啟Visual Studio。

上述安裝過程如圖3-5所示。


圖3-5. 安裝NuGet包管理器

Install the Web API Client Libraries
安裝Web API客戶端庫

After NuGet Package Manager is installed, add the Web API Client Libraries package to your project.
安裝NuGet包管理器後,把Web API客戶端庫包添加到你的項目。步驟如下:
1.From the Tools menu, select Library Package Manager. Note: If do you not see this menu item, make sure that NuGet Package Manager installed correctly.
從「工具」菜單選擇「庫包管理器」。註:如果看不到這個菜單項,請確保已正確安裝了NuGet包管理器。
2.Select Manage NuGet Packages for Solution...
選擇「管理解決方案的NuGet包…」
3.In the Manage NuGet Packages dialog, select Online.
在「管理NuGet包」對話框中,選擇「在線」。
4.In the search box, type "Microsoft.AspNet.WebApi.Client".
在搜索框中輸入「Microsoft.AspNet.WebApi.Client」。
5.Select the ASP.NET Web API Self Host package and click Install.
選擇「ASP.NET Web API自託管包」,並點擊「安裝」。
6.After the package installs, click Close to close the dialog.
這個包安裝後,點擊「關閉」,關閉此對話框。

上述安裝步驟如圖3-6所示。


圖3-6. 安裝Web API客戶端庫

Initialize HttpClient
初始化HttpClient

From Solution Explorer, open the file MainWindow.xaml.cs. Add the following code.
在「解決方案資源管理器」中,打開MainWindow.xaml.cs文件。添加以下代碼:

namespace WpfProctClient
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Windows;
public partial class MainWindow : Window
{
HttpClient client = new HttpClient();
ProctsCollection _procts = new ProctsCollection();
public MainWindow()
{
InitializeComponent();
client.BaseAddress = new Uri("http://localhost:9000");
client.DefaultRequestHeaders.Accept.Add(
new ("application/json"));
this.ProctsList.ItemsSource = _procts;
}
}
}
This code creates a new instance of HttpClient. It also sets the base URI to "http://localhost:9000/", and sets the Accept header to "application/json", which tells the server to send data in JSON format.
這段代碼創建了一個新的HttpClient實例。也把基URI設置為「http://localhost:9000/」,並且把Accept報頭設置為「application/json」,這是告訴伺服器,以JSON格式發送數據。

Notice that we also created a new ProctsCollection class and set it as the binding for the ListBox.
注意,我們也創建了一個新的ProctsCollection類,並把它設置為對ListBox的綁定。

Getting a Resource (HTTP GET)
獲取資源(HTTP GET)

If you are targeting .NET Framework 4.5, the async and await keywords make it much easier to write asynchronous code.
如果你的目標是.NET Framework 4.5(意即,你所開發的應用程序將在.NET 4.5平台上運行 — 譯者注),async和await關鍵字會讓你很容易編寫非同步代碼。

If you are targeting .NET Framework 4.0 with Visual Studio 2012, you can install the Async Targeting Pack to get async/await support.
如果你的目標是使用Visual Studio 2012的.NET Framework 4.0,可以安裝Async Targeting Pack來獲得async/await支持。

The following code queries the API for a list of procts. Add this code to the MainWindow class:
以下代碼查詢產品列表API。將此代碼添加到MainWindow類:

private async void GetProcts(object sender, RoutedEventArgs e)
{
try
{
btnGetProcts.IsEnabled = false;
var response = await client.GetAsync("api/procts");
response.EnsureSuccessStatusCode(); // Throw on error code(有錯誤碼時報出異常).
var procts = await response.Content.ReadAsAsync<IEnumerable<Proct>>();
_procts.CopyFrom(procts);
}
catch (Newtonsoft.Json.JsonException jEx)
{
// This exception indicates a problem deserializing the request body.
// 這個異常指明了一個解序列化請求體的問題。
MessageBox.Show(jEx.Message);
}
catch (HttpRequestException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
btnGetProcts.IsEnabled = true;
}
}
The GetAsync method sends an HTTP GET request. If the HTTP response indicates success, the response body contains a list of procts in JSON format. To parse the list, call ReadAsAsync. This method reads the response body and tries to deserialize it to a specified CLR type.
GetAsync方法發送一個HTTP GET請求。如果HTTP響應指示成功,響應體會含有一個JSON格式的產品列表。要解析這個列表,調用ReadAsAsync。這個方法會讀取響應體,並試圖把它解序列化成一個具體的CLR類型。

As their names imply, GetAsync and ReadAsAsync are asynchronous methods, meaning they return immediately, without waiting for the operation to complete. The await keyword suspends execution until the operation completes. For example:
正如其名稱所暗示的,GetAsync和ReadAsAsync是非同步方法,意即,它們立即返回,不會等待操作完成。await關鍵字會掛起執行,直到操作完成。例如:

var response = await client.GetAsync("api/procts");
The code that appears after this statement does not execute until the HTTP request is completed. But that does not mean the event handler blocks, waiting for GetAsync to complete. Just the opposite — control returns to the caller. When the HTTP request is completed, execution continues from the point where it was suspended.
出現在這條語句之後的代碼直到HTTP請求完成時才會執行。但這並不意味著事件處理器(event handler,也可以叫做事件處理程序 — 譯者注)會阻塞,以等待GetAsync完成。恰恰相反 — 控制會返回給調用者。當HTTP請求完成時,執行會從掛起點繼續。

If a method uses await, it must have the async modifier:
如果一個方法使用await,它必須有async修飾符:

private async void GetProcts(object sender, RoutedEventArgs e)
Without the await keyword, you would need to call ContinueWith on the Task object:
沒有這個await關鍵字,你就需要調用Task對象上的ContinueWith:

private void GetProcts(object sender, RoutedEventArgs e)
{
btnGetProcts.IsEnabled = false;
client.GetAsync("api/procts/2").ContinueWith((t) =>
{
if (t.IsFaulted)
{
MessageBox.Show(t.Exception.Message);
btnGetProcts.IsEnabled = true;
}
else
{
var response = t.Result;
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsAsync<IEnumerable<Proct>>().
ContinueWith(t2 =>
{
if (t2.IsFaulted)
{
MessageBox.Show(t2.Exception.Message);
btnGetProcts.IsEnabled = true;
}
else
{
var procts = t2.Result;
_procts.CopyFrom(procts);
btnGetProcts.IsEnabled = true;
}
}, TaskScheler.());
}
}
}, TaskScheler.());
}
This type of code is difficult to get right, so it's recommended to target .NET 4.5, or if that's not possible, install the Async Targeting Pack.
這種型式的代碼難以正確,因此建議把目標定為.NET 4.5,或者,如果這不可能,需安裝Async Targeting Pack(Async目標包)。

F. 使用aspnet.identity 身份驗證的框架中,怎麼對現有用戶進行刪除

首先讓我先更新 API 項目

我先 API 項目進行必要修改修改完再切換 Web 項目客戶端進行更新

第1步:我需要資料庫

能做任何操作前我需要先創建資料庫本例使用 SQL Server Express沒安裝載 SQL Server Express安裝完創建名 CallingWebApiFromMvc 資料庫第步要做

Api 項目需要資料庫連接字元串否則我寸步難行面段代碼插入 Api 項目Web.config 文件:

認證(Identity)框架自創建我管理用戶所需要員關系表現需要擔提前創建

第2步:添加相關Nuget包

接我添加用於OWINWindows認證Nuget包打包管理控制台切換Api項目預設項目輸入命令:

Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.AspNet.Identity.Owin

使用些包我應用啟OWIN伺服器通EntityFramework我用戶保存SQL Server

第3步:添加管理用戶Identity類

我使用基於Windows認證機制Entity框架管理資料庫相關業務首先我需要添加些用於處理類Api項目添加Identity目錄作我要添加類命名空間添加類:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext
{ public ApplicationDbContext() : base("ApiFromMvcConnection") {}
public static ApplicationDbContext Create()
{ return new ApplicationDbContext();
}
}

注意我傳給基類構造函數參數ApiFromMvcConnection要Web.config連接字元串name相匹配

public class ApplicationUserManager : UserManager
{ public ApplicationUserManager(IUserStore store) : base(store)
{
} public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
{ var manager = new ApplicationUserManager(new UserStore (context.Get ()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator (manager)
{
= false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
}; var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider (dataProtectionProvider.Create("ASP.NET Identity"));
} return manager;
}
}

第4步:添加OWIN啟類

讓我應用程序作OWIN伺服器運行我需要應用程序啟初始化我通啟類做點我裝點類
OwinStartup屬性應用程序啟觸發意味著我擺脫Global.asax移
Application_Start代碼轉換我新啟類

using Microsoft.Owin;

[assembly: OwinStartup(typeof(Levelnis.Learning.CallingWebApiFromMvc.Api.Startup))]
namespace Levelnis.Learning.CallingWebApiFromMvc.Api
{
using System;
using System.Web.Http;
using Identity;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Providers;
public class Startup
{ public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext (ApplicationUserManager.Create); var oAuthOptions = new
{
TokenEndpointPath = new PathString("/api/token"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(oAuthOptions);
}
}
}

應用程序啟我建立自伺服器我配置令牌端點並設置自自定義提供商我用我用戶進行身份驗證我例我使用ApplicationOAuthProvider類讓我看看現:

第5步:添加OAuth提供商

public class ApplicationOAuthProvider :
{ public override Task ValidateClientAuthentication( context)
{
context.Validated();
return Task.FromResult (null);
}
public override async Task GrantResourceOwnerCredentials( context)
{
var userManager = context.OwinContext.GetUserManager ();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect."); return;
}
var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); var cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); var properties = CreateProperties(user.UserName); var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
private static AuthenticationProperties CreateProperties(string userName)
{
var data = new Dictionary
{
{
"userName", userName
}
};
return new AuthenticationProperties(data);
}
}

我興趣2種第ValidateClientAuthentication驗證客戶端我客戶端所返
功非同步簽名沒非同步調用發我離非同步修改我必須返任務自我增加名
看起像:

public class ApplicationUser : IdentityUser
{ public async Task GenerateUserIdentityAsync(UserManager manager, string authenticationType)
{
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
return userIdentity;
}
}

第6步:注冊新用戶 - API端
所我位所Identity類管理用戶讓我看看RegisterController新用戶保存我資料庫接受RegisterApi模式簡單:

public class RegisterApiModel
{
[Required]
[EmailAddress] public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password {
get; set;
}

[Required]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

控制器本身注冊功返200 OK響應驗證失敗則返401錯誤請求響應

public class RegisterController : ApiController
{ private ApplicationUserManager UserManager
{ get
{ return Request.GetOwinContext().GetUserManager ();
}
} public IHttpActionResult Post(RegisterApiModel model)
{ if (!ModelState.IsValid)
{ return BadRequest(ModelState);
} var user = new ApplicationUser
{
Email = model.Email,
UserName = model.Email,
EmailConfirmed = true
};
var result = UserManager.Create(user, model.Password);
return result.Succeeded ? Ok() : GetErrorResult(result);
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (result.Errors != null)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
}

G. rails相較於.net WebAPI有什麼優勢,有什麼劣勢

vs中,打開工具=>nuget程序包管理器=>程序包管理器控制台,然後其中一行一行地輸入以下的更新指令。Update-PackageMicrosoft.AspNet.WebApi-Version5.2.2漢化包Update-PackageMicrosoft.AspNet.WebApi.Client.zh-Hans-Version5.2.2Update-PackageMicrosoft.AspNet.WebApi.Core.zh-Hans-Version5.2.2Update-PackageMicrosoft.AspNet.WebApi.WebHost.zh-Hans-Version5.2.2Update-PackageEntityFramework-Version6.0.1Update-PackageEntityFramework.zh-Hans-Version6.0.1Update-PackageMicrosoft.AspNet.Mvc-Version5.2.2Update-PackageMicrosoft.AspNet.Mvc.zh-Hans-Version5.2.2Update-PackageMicrosoft.AspNet.WebApi.HelpPage-Version5.2.2Update-PackageMicrosoft.AspNet.WebApi.OData-Version5.2.2Update-PackageMicrosoft.AspNet.WebApi.Tracing-Version5.2.2上面package的版本號參考了vs2013中的webapi項目模板中的版本號。引入這些包的過程中,vs有可能提示要重啟vs,請重啟vs。錯誤:「未能找到元數據文件」更新完package之後,重新編譯,有可能出現「未能找到元數據文件」。解決的方法是找到出錯的項目,然後去掉報錯的引用項,然後再重新引用。錯誤:預定義的類型"Microsoft.CSharp.RuntimeBinder.Binder"未定義或未導入錯誤再次編譯,有可能出現錯誤提示「預定義的類型"Microsoft.CSharp.RuntimeBinder.Binder"未定義或未導入」,解決的方法是:(1)用記事本打開項目文件(後綴名為.csproj),找到項,可能會找到多個,選擇其中一個,在裡面加入(2)保存項目文件,然後重新載入項目項目文件。

H. 如何讓webapi的版本降為.net4.0

vs中,打開 工具 => nuget程序包管理器 => 程序包管理器控制台,然後其中一行一行地輸入以下的更新指令。
Update-Package Microsoft.AspNet.WebApi -Version 5.2.2

漢化包
Update-Package Microsoft.AspNet.WebApi.Client.zh-Hans -Version 5.2.2
Update-Package Microsoft.AspNet.WebApi.Core.zh-Hans -Version 5.2.2
Update-Package Microsoft.AspNet.WebApi.WebHost.zh-Hans -Version 5.2.2

Update-Package EntityFramework -Version 6.0.1
Update-Package EntityFramework.zh-Hans -Version 6.0.1

Update-Package Microsoft.AspNet.Mvc -Version 5.2.2
Update-Package Microsoft.AspNet.Mvc.zh-Hans -Version 5.2.2

Update-Package Microsoft.AspNet.WebApi.HelpPage -Version 5.2.2

Update-Package Microsoft.AspNet.WebApi.OData -Version 5.2.2

Update-Package Microsoft.AspNet.WebApi.Tracing -Version 5.2.2

上面package的版本號參考了vs2013中的webapi項目模板中的版本號。引入這些包的過程中,vs有可能提示要重啟vs,請重啟vs。
錯誤:「未能找到元數據文件」
更新完package之後,重新編譯,有可能出現「未能找到元數據文件」。
解決的方法是找到出錯的項目,然後去掉報錯的引用項,然後再重新引用。
錯誤:預定義的類型"Microsoft.CSharp.RuntimeBinder.Binder"未定義或未導入 錯誤
再次編譯,有可能出現錯誤提示「預定義的類型"Microsoft.CSharp.RuntimeBinder.Binder"未定義或未導入」 ,解決的方法是:
(1)用記事本打開項目文件(後綴名為 .csproj ),找到<ItemGroup>項,可能會找到多個,選擇其中一個,在裡面加入
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />

(2)保存項目文件,然後重新載入項目項目文件。

I. configureglobal什麼時候執行

在VS.NET 2013中,新建WebAPI項目,代碼總的
GlobalConfiguration.Configure(WebApiConfig.Register);
編譯時會提示:System.Web.Http.GlobalConfiguration 並不包含「Configure」的定義
實際是因為vs2013默認沒有安裝webapi的包,解決方法如下:

通過 工具->庫程序包管理器->程序包管理器控制台 打開 管理控制台
在控制台輸入如下命令:

Install-Package Microsoft.AspNet.WebApi.WebHost

J. 求ASP.NET程序設計(C#版)(崔淼等)的電子版書,機械工業出版社

別看這些老技術了,c#做web開發,現在建議學net core.

作為一個.NET Web開發者,我最傷心的時候就是項目開發部署時面對Windows Server上貧瘠的解決方案,同樣是神器Nginx,Win上的Nginx便始終不如Linux上的,你或許會說「幹嘛不用windows自帶的NLB呢」,那這就是我這個小鳥的從眾心理了,君不見Stack Overflow 2016最新架構中,用的負載和緩存技術也都是採用在Linux上已經成熟的解決方案嗎。沒辦法的時候找個適合的解決辦法是好事,有辦法的時候當然要選擇最好的解決辦法。

什麼ASPNET Core

ASP.NET Core 是一個新的開源和跨平台的框架,用於構建如 Web 應用、物聯網(IoT)應用和移動後端應用等連接到互聯網的基於雲的現代應用程序。ASP.NET Core 應用可運行於 .NET Core 和完整的 .NET Framework 之上。它整合了原來ASP.NET中的MVC和WebApi框架,你可以在 Windows、Mac 和 Linux 上跨平台的開發和運行你的 ASP.NET Core 應用。