我有以下Web API(GET):
public class UsersController : ApiController
{
public IEnumerable<Users> Get(string firstName, string LastName, DateTime birthDate)
{
// Code
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个GET,所以我可以这样称呼它:
http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01
Run Code Online (Sandbox Code Playgroud)
并接收用户的xml结果.
是否可以将参数封装到一个类中,如下所示:
public class MyApiParameters
{
public string FirstName {get; set;}
public string LastName {get; set;}
public DateTime BirthDate {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
然后有:
public IEnumerable<Users> Get(MyApiParameters parameters)
Run Code Online (Sandbox Code Playgroud)
我已经尝试过,无论何时我试图获得结果http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01
,parameter
都是null.
在ASP.NET 4.5 MVC 4 Web API项目中,我想添加一个自定义HttpMessageHandler
.我已经更改了WebApiConfig
类(在\ App_Satrt\WebApiConfig.cs中),如下所示:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new MyCustomizedHttpMessageHandler()
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我发展了MyCustomizedHttpMessageHandler
:
public class MyCustomizedHttpMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IPrincipal principal = new GenericPrincipal(
new GenericIdentity("myuser"), new string[] { "myrole" });
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return Task<HttpResponseMessage>.Factory.StartNew(() => …
Run Code Online (Sandbox Code Playgroud) 如果我想为ASP.NET MVC控制器实现依赖注入,我可以使用IControllerFactory
interface创建工厂类,然后在Global.asax.cs中注册它,如:
ControllerBuilder.Current.SetControllerFactory(controllerFactory)
Run Code Online (Sandbox Code Playgroud)
(参考:http://www.dotnetcurry.com/ShowArticle.aspx?ID = 786)
现在我的问题是:
我怎样才能为IHttpControllerActivator
派生类设置工厂?
我们在ASP.NET MVC 4.0中有什么东西:
HttpControllerBuilder.Current.SetApiControllerActivator(httpControllerActivator)
Run Code Online (Sandbox Code Playgroud)
?
更新:
我想添加我当前的代码,理解这个案例可能会有所帮助:
我定制的HttpControllerActivator:
public class MyCustomApiActivator : DefaultHttpControllerActivator
//or IHttpControllerActivator ?
{
private readonly Dictionary<string, Func<HttpRequestMessage, IHttpController>> _apiMap;
public MyCustomApiActivator(IMyRepository repository)
{
if (repository == null)
{
throw new ArgumentException("repository");
}
_apiMap = new Dictionary<string, Func<HttpRequestMessage, IHttpController>>();
controllerMap["Home"] = context => new HomeController();
_apiMap["MyCustomApi"] = context => new MyCustomApiController(repository);
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{ …
Run Code Online (Sandbox Code Playgroud) 我在Azure DevOps存储库中有一个ASP.NET Core项目,使用DevOps构建管道可以构建它.但是,该版本的发布总是因此错误而失败:
错误:找不到包含指定模式的包:D:\ a\r1\a***.zip
这是我的azure.pipelines.yml
档案:
pool:
vmImage: 'vs2017-win2016'
variables:
buildConfiguration: 'Release'
steps:
- script: dotnet build ".\src\MyProject.sln" --configuration $(buildConfiguration)
displayName: 'dotnet build $(buildConfiguration)'
- script: dotnet publish ".\src\MyProject.sln" --configuration $(buildConfiguration) --output $(Build.ArtifactStagingDirectory)
displayName: 'dotnet publish $(buildConfiguration)'
- task: PublishBuildArtifacts@1
pathtoPublish: '$(Build.ArtifactStagingDirectory)'
artifactName: 'drop'
publishLocation: 'Container'
Run Code Online (Sandbox Code Playgroud)
日志
初始化工作:
2018-11-02T05:31:14.7337716Z ##[section]Starting: Initialize job
2018-11-02T05:31:14.7338264Z Current agent version: '2.141.1'
2018-11-02T05:31:14.7365208Z Prepare release directory.
2018-11-02T05:31:14.7379296Z ReleaseId=4, TeamProjectId=ea66a316-xxxx-xxxx-xxxx-866fc594b83f, ReleaseDefinitionName=New release pipeline
2018-11-02T05:31:14.7461870Z Release folder: D:\a\r1\a …
Run Code Online (Sandbox Code Playgroud) 我正在尝试设计模块化Web API应用程序(它不是MVC应用程序!),其中管理员角色的用户可以在不重新启动ASP.NET应用程序的情况下添加或删除模块.
ApiController
.因此,主Web API项目中唯一的控制器是:
[RoutePrefix("api/modules")]
public class ModulesController : ApiController
{
private ModuleService _moduleService = new ModuleService();
// GET: api/Modules
[Route]
public IEnumerable<string> Get()
{
return _moduleService.Get().Select(a => a.FullName);
}
// POST: api/Modules/{moduleName}
[Route("{id}")]
public void Post(string id)
{
Assembly _assembly;
var result = _moduleService.TryLoad(id, out _assembly);
if(!result) throw new Exception("problem loading " + id);
// Refresh routs or add the new rout
Configuration.Routes.Clear();
Configuration.MapHttpAttributeRoutes(); …
Run Code Online (Sandbox Code Playgroud) 我的代码编译并运行没有错误; 但是,它没有按照我的预期呈现.
理论:
我想使用多个布局页面.
"基础"布局应仅包括解决方案正在使用的样式和javascript文件.
另一个布局应该有html内容或包装器.这种布局目前似乎是多余的,但是我的上级向我保证它会带来未来的伟大.例如具有多个标题或在某些页面上没有页眉或页脚的能力.主要的是拥有多个ContentLayouts但只有一个常见的BaseLayout
代码:
_BaseLayout
<html>
<head>
<link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="@Url.Content("~/Scripts/common.js")"></script>
@RenderSection("JavaScript", false)
@RenderSection("Css", false)
</head>
<body>
@RenderBody()
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
_ContentLayout
@{
Layout = "~/Views/Shared/_BaseLayout.cshtml";
}
@RenderSection("JavaScript", false)
@RenderSection("Css", false)
<div class="page">
<section class="wrapper">
@RenderBody()
</section>
</div>
Run Code Online (Sandbox Code Playgroud)
View.cshtml
@{
Layout = "~/Views/Shared/_ContentLayout.cshtml";
}
@section JavaScript
{
<script type="text/javascript">
(function ($) {
$(function () {
//do stuff;
});
} (jQuery));
</script>
}
<div>
//html content
</div>
Run Code Online (Sandbox Code Playgroud)
就像我之前说过的那样有效.问题是当我查看页面源时,视图中的脚本在_ContentLayout中呈现,因此落在指定的脚本区域之外.我可以将脚本代码"踢"到下一个布局吗?这将允许所有脚本代码位于同一区域.
部署新版本的 ASP.NET 网站后,是否有办法强制客户端浏览器刷新缓存项,尤其是图像、CSS 和 Javascript 文件?
\n\n问题是我不能\xe2\x80\x99 到处告诉每个使用该网站的人点击CTRL+ F5。我怎样才能强制浏览器这样做?
\n我们可以在 NuGet 库中找到两个独立的包:
两者似乎都定期更新并有数百万次下载。
我知道它System.IdentityModel.Tokens.Jwt
依赖于Microsoft.IdentityModel.Tokens
,但我不知道应该在我的 ASP.NET Core 2.0 应用程序中使用哪个。
我现在正在使用Microsoft.IdentityModel.Tokens
,它足以创建 JWT 令牌并验证它们。
我需要添加System.IdentityModel.Tokens.Jwt
到我的项目中并更改任何代码吗?
PS:我在这个项目中没有使用 Azure 服务。
我有一个参考的netstandard 2.0项目System.ComponentModel.Annotations
。它可以在本地计算机上很好地构建,但是当我尝试使用Azure DevOps管道构建它时,出现以下错误:
...警告MSB3245:无法解析此引用。无法找到程序集“ System.ComponentModel.Annotations”。检查以确保程序集在磁盘上。如果您的代码需要此引用,则可能会出现编译错误。[/home/vsts/work/1/s/src/MyProj/MyProj.csproj]
... MyProj / MyClass.cs(2,29):错误CS0234:类型或名称空间名称'DataAnnotations'在名称空间'System.ComponentModel'中不存在(您是否缺少程序集引用?)[/ home / vsts /work/1/s/src/MyProj/MyProj.csproj]
该错误是不言自明的,并且我理解该错误的含义,但问题是我应该如何解决此问题,以满足Azure DevOps的构建?
azure-devops azure-pipelines .net-standard .net-standard-2.0
我们可以Route
在ASP.NET Core 的模板中使用破折号(-)吗?
// GET: api/customers/5/orders?active-orders=true
[Route("customers/{customer-id}/orders")]
public IActionResult GetCustomerOrders(int customerId, bool activeOrders)
{
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
(以上代码无效)
虽然我知道这个问题/答案(单元测试一种调用另一种方法的方法),但仍然不确定什么是对同一类调用另一个公共方法的方法进行单元测试的最佳方法?
我做了一个示例代码(也可以在这里看到:dotnetfiddle.net/I07RMg)
public class MyEntity
{
public int ID { get; set;}
public string Title { get; set;}
}
public interface IMyService
{
MyEntity GetEntity(int entityId);
IEnumerable<MyEntity> GetAllEntities();
}
public sealed class MyService : IMyService
{
IRepository _repository;
public MyService(IRepository repository)
{
_repository = repository;
}
public MyEntity GetEntity(int entityId)
{
var entities = GetAllEntities();
var entity = entities.SingleOrDefault(e => e.ID == entityId);
if (entity == null)
{
entity = new MyEntity { ID = -1, …
Run Code Online (Sandbox Code Playgroud) asp.net ×2
asp.net-core ×2
azure-devops ×2
c# ×2
asp.net-4.5 ×1
asp.net-mvc ×1
azure-pipelines-release-pipeline ×1
html5 ×1
javascript ×1
jwt ×1
razor ×1
signalr ×1
signalr-2 ×1
unit-testing ×1