在WebAPI项目中,我有一个控制器,它根据用户输入的值检查产品的状态.
让我们说他们输入"123"并且响应应该是"状态":1,和产品列表.如果输入"321",则"状态"为0,以及产品列表.
我的问题是,如何在WebAPI控制器中构建正确的字符串.
[Route("{value:int}")]
public string GetProducts(int value)
{
var json = "";
var products = db.Products;
if (products.Any())
{
foreach (var s in products)
{
ProductApi product = new ProductApi();
product.Name = s.Name;
json += JsonConvert.SerializeObject(supplier);
}
}
var status = db.Status;
if (status.Any())
{
json += "{status:1}";
}
else
{
json += "{status:0}";
}
return json;
}
public class ProductApi
{
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
此外,此输出/响应是否有效?
[
{
"id":1,
"name":"product name"
},
{
"id":2, …
Run Code Online (Sandbox Code Playgroud) 我在Model-First模式(= EDMX)中使用System.Data.SQLite 1.0.90与VS2013和EntityFramework 5.
我创建了一个包含表的新SQLite数据库:
CREATE TABLE [..]
[Test1integer] integer,
[Test2int] int,
[Test3smallint] smallint,
[Test4tinyint] tinyint,
[Test5bigint] bigint,
[Test6money] money,
[Test7float] float,
[Test8real] real,
[Test9decimal] decimal,
[Test10numeric18_5] numeric(18,5), [..]
Run Code Online (Sandbox Code Playgroud)
相关部分是Test7float
和Test8real
.
从数据库执行更新模型后... EDMX现在包含:
<Property Name="Test1integer" Type="integer" />
<Property Name="Test2int" Type="int" />
<Property Name="Test3smallint" Type="smallint" />
<Property Name="Test4tinyint" Type="tinyint" />
<Property Name="Test5bigint" Type="integer" />
<Property Name="Test6money" Type="decimal" Precision="53" Scale="0" />
<Property Name="Test7float" Type="real" />
<Property Name="Test8real" Type="real" />
<Property Name="Test9decimal" Type="decimal" Precision="53" Scale="0" />
<Property …
Run Code Online (Sandbox Code Playgroud) 几个星期以来,我一直在研究ASP.NET Core.我试图在此基础上博客实现的东西: 微服务
我的project.json
情况如下:
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics": "1.0.0-rc1-*",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"EntityFramework.Core": "7.0.0-rc1-final",
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer.Design": "7.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Formatters.Json": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final",
"System.Security.Cryptography.Algorithms": "4.0.0-beta-23516"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
"ef": "EntityFramework.Commands"
},
"frameworks": {
"dnxcore50": {
"dependencies": {
}
}
},
"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
"**.user",
"**.vspscc"
]
}
Run Code Online (Sandbox Code Playgroud)
而ConfigureServices
在方法Startup.cs
如下:
public void ConfigureServices(IServiceCollection services)
{
//Registering Authorization Database
AutorizationAccessRegisteration.RegisterComponents(services, …
Run Code Online (Sandbox Code Playgroud) 所以我从头开始构建WebAPI,包括我在网上找到的一些最佳实践,例如依赖注入和使用自动映射器的域< - > DTO映射等.
我的API控制器现在看起来与此类似
public MyController(IMapper mapper)
{
}
Run Code Online (Sandbox Code Playgroud)
和AutoMapper注册表:
public AutoMapperRegistry()
{
var profiles = from t in typeof(AutoMapperRegistry).Assembly.GetTypes()
where typeof(Profile).IsAssignableFrom(t)
select (Profile)Activator.CreateInstance(t);
var config = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
For<MapperConfiguration>().Use(config);
For<IMapper>().Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));
}
Run Code Online (Sandbox Code Playgroud)
我也在构建一些测试用例,实现MOQ,这是我感到有些不确定的地方.每当调用我的控制器时,我需要传递一个IMapper,如下所示:
var mockMapper = new Mock<IMapper>();
var controller = new MyController(mockMapper.Object);
Run Code Online (Sandbox Code Playgroud)
但是,如何配置IMapper以获得正确的映射?在配置Mapper之前重新创建我已经创建的相同逻辑会感觉多余.所以我想知道这样做的推荐方法是什么?
我正在致力于优化我们的实体框架代码,目前我面临着一个我不确定如何解决的问题。
我们使用Azure SQL + Code-First Entity Framework 6.1.3 + Asp.net Web Api v2。端点托管在云中,我使用它进行测试。
我有一个 API 操作,用于获取过滤、排序和分页数据。这是我处理数据的简化代码:
var entities = DbContext.Services
.Include(q => q.Consumer.Building.Address.Country)
.Include(q => q.Consumer.Building.Address.State);
entities = entities.OrderBy(x => x.Consumer.RegisteredAt);
entities = entities.Where(x => x.IsDeleted == false);
entities = entities.Where(x => userId.HasValue ? x.Owner.Id == userId ? true); //this part comes from deep internals, so I cannot change it quickly
var page = entities = entities.Skip(skip).Take(take).ToList();
var count = entities.Count();
var dtoPage = Mapper.Map<IEnumerable<ServiceDto>>(page);
return Page<ServiceDto>(dtoPage, count); …
Run Code Online (Sandbox Code Playgroud) c# entity-framework azure entity-framework-6 azure-sql-database
我试图了解 DI 在新的 ASP Core 中是如何工作的。通过教程,我使其适用于控制器,但无法使其适用于模型。例如,我有一个 AuthController,我向它注入了数据库上下文,但现在,由于我有更多控制器,共享相同的模型,即Authentication
,我想将上下文注入到模型本身。这是我的一些代码:
来自Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<GameContext>(options => options.UseSqlServer(@"Data Source=DESKTOP-USER\SQLEXPRESS;Initial Catalog=Db7;Integrated Security=True;Connect Timeout=30;"));
}
Run Code Online (Sandbox Code Playgroud)
这是我在控制器中使用它的方法:
[Route("api/[controller]")]
public class AuthController : Controller
{
public GameContext db;
public AuthController(GameContext context)
{
db = context;
}
[HttpPost]
[Route("login")]
public LoginResponseModel Login([FromBody] LoginModel user) //public Models.VM.LoginModel Login([FromBody] Models.VM.LoginModel user)
{
//query user
var detectedUser = db.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == HelperClass.Md5(user.Password);
Run Code Online (Sandbox Code Playgroud)
如果我从控制器中删除上下文部分,并将其移动到模型中,我将无法再次实例化它,因为构造函数需要一个参数(将自动注入?)
public class Authentication
{
public GameContext db;
public …
Run Code Online (Sandbox Code Playgroud) 我很难弄清楚如何使用反应式扩展在 C# 中创建事件总线,而无需使用主题类,据我所知,不建议这样做。
大多数 IEvent 是我自己的,但有些像鼠标和键盘事件将由 WPF 提供。
我更喜欢将事件发布到事件总线的想法,而不是使用 Observable.FromEventPattern 随处使用事件处理程序,因为其中一些事件有时仅由订阅者记录而不执行。
这是显示我正在尝试做的事情的片段。
public interface IEvent { } // marker interface
public class BarcodeReaderEvent : EventArgs, IEvent
{ }
public class MouseEvent : EventArgs, IEvent
{ }
public class MyEventBus
{
private static IObservable<IEvent> eventBus = ??
public void Post<IEvent>(IEvent theEvent)
{
// What goes here?
}
public IDisposable Subscribe()
{
return ??
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个小例子来使用|| 运营商Where()
但可能出现问题:
var list = new List<string>
{
"One",
"Two",
"Three"
};
string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
foreach(var number in numbers)
{
Console.WriteLine(number);
// output:
// One
// Two
// Three
}
s = null;
numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
foreach(var number in numbers)
{
Console.WriteLine(number);
// output:
// One
// Two
// Three
}
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,为什么!string.IsNullOrEmpty(x)
在我们x == s
真的时候仍然检查?
我明白了:
if (A …
Run Code Online (Sandbox Code Playgroud) c# ×6
linq ×2
asp.net-core ×1
automapper ×1
azure ×1
json ×1
moq ×1
sqlite ×1
structuremap ×1
unit-testing ×1