
课程咨询: 400-996-5531 / 投诉建议: 400-111-8989
认真做教育 专心促就业
ASP.NET Core 使用protobuf:这篇文章是对上一篇文章的补充,各位同学结合到上一篇看就会理解了!
整个Startup.cs代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DamService.Data;
using DamService.Models;
using DamService.Services;
using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace DamService
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped(provider => new Hammergo.Data.DamWCFContext(Configuration.GetConnectionString("OdataDBConnectionString")));
services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.AddMvc(options =>
{
options.InputFormatters.Add(new ProtobufInputFormatter());
options.OutputFormatters.Add(new ProtobufOutputFormatter());
options.FormatterMappings.SetMediaTypeMappingForFormat("protobuf", MediaTypeHeaderValue.Parse("application/x-protobuf"));
});
// Add application services.
//services.AddTransient();
//services.AddTransient();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
// app.UseDatabaseErrorPage();
// app.UseBrowserLink();
//}
//else
//{
// app.UseExceptionHandler("/Home/Error");
//}
app.UseExceptionHandler(_exceptionHandler);
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
private void _exceptionHandler(IApplicationBuilder builder)
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/plain";
var error = context.Features.Get();
if (error != null)
{
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
}
}
}
上面的
services.AddScoped(provider => new Hammergo.Data.DamWCFContext(Configuration.GetConnectionString("OdataDBConnectionString")));
是我自己的数据库连接,可以使用自己的,也可以不用,我用的是EntityFrameWork 6.1.3 不是core,目前core还有一些功能没有,暂时不使用。
添加一个测试用的Controller,
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Hammergo.Data;
using System.Linq.Expressions;
using System.Data.Entity;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DamService.Controllers
{
public class AppsController : Controller
{
private readonly DamWCFContext _dbContext;
private readonly ILogger _logger;
public AppsController(
DamWCFContext dbContext,
ILoggerFactory loggerFactory)
{
_dbContext = dbContext;
_logger = loggerFactory.CreateLogger();
}
[HttpGet]
public async Task> Top10()
{
return await _dbContext.Apps.Take(10).ToListAsync();
}
}
}
客户端测试代码:
var client = new HttpClient { BaseAddress = new Uri("#:40786/") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
HttpResponseMessage response = null;
//test top 10
string uri = "Apps/Top10";
Trace.WriteLine("\n Test {0}.", uri);
response = client.GetAsync(uri).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsAsync>(new[] { new ProtoBufFormatter() }).Result;
Assert.AreEqual(result.Count, 10, "反序列化失败");
Console.WriteLine("{0} test success!", uri);
}
else
{
var message = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("{0} ({1})\n message: {2} ", (int)response.StatusCode, response.ReasonPhrase, message);
}
#:40786/
这里40786为服务端口,Fiddler表示使用了Fiddler代理,这样在使用时需要开启Fiddler,如果不使用Fidller,将URI修改为:http://localhost:40786/