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
简介:全书共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 应用。