小编Toh*_*hid的帖子

如何开发ASP.NET Web API以接受复杂对象作为参数?

我有以下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-mvc-4 asp.net-web-api

41
推荐指数
1
解决办法
3万
查看次数

如何在Web API中实现HttpMessageHandler?

在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)

c# asp.net-mvc-4 asp.net-4.5 asp.net-web-api

16
推荐指数
2
解决办法
3万
查看次数

是否有适用于ASP.NET Web API的HttpControllerBuilder?

如果我想为ASP.NET MVC控制器实现依赖注入,我可以使用IControllerFactoryinterface创建工厂类,然后在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)

dependency-injection asp.net-mvc-4 asp.net-web-api

13
推荐指数
1
解决办法
6375
查看次数

Azure DevOps管道版本错误:找不到包含指定模式的包:D:\ a\r1\a\**\*.zip

我在Azure DevOps存储库中有一个ASP.NET Core项目,使用DevOps构建管道可以构建它.但是,该版本的发布总是因此错误而失败:

错误:找不到包含指定模式的包:D:\ a\r1\a***.zip

我已经检查了这个这个 Q/As,但无法弄清楚解决方案.

这是我的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)

更多细节

发布管道错误: Azure DevOps发布管道错误

日志

初始化工作:

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)

azure-devops azure-pipelines-release-pipeline

12
推荐指数
5
解决办法
4604
查看次数

模块化ASP.NET Web API:如何在运行时向Web API添加/删除路由

我正在尝试设计模块化Web API应用程序(它不是MVC应用程序!),其中管理员角色的用户可以在不重新启动ASP.NET应用程序的情况下添加或删除模块.

  • 模块:每个模块都是一个程序集(.dll文件),它至少包含一个派生自的类ApiController.
  • 路由基于ASP.NET Web API 2中的"属性路由"
  • 模块(组件)的生产不在本问题的范围内.
  • 模块(程序集文件)被复制到项目根目录中的〜/ plugins /文件夹中/从中删除.这个过程也不属于这个问题的范围.
  • 主要的ASP.NET Web API项目基本上只有一个控制器来管理(添加/删除)模块.其他控制器将作为模块添加.

因此,主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)

asp.net-web-api asp.net-web-api-routing asp.net-web-api2

7
推荐指数
1
解决办法
3795
查看次数

使用嵌套布局在一个部分中呈现所有Javascript代码

我的代码编译并运行没有错误; 但是,它没有按照我的预期呈现.

理论:

我想使用多个布局页面.

"基础"布局应仅包括解决方案正在使用的样式和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中呈现,因此落在指定的脚本区域之外.我可以将脚本代码"踢"到下一个布局吗?这将允许所有脚本代码位于同一区域.

javascript html5 razor asp.net-mvc-3

5
推荐指数
1
解决办法
8962
查看次数

是否有类似于Web API帮助页面的SignalR自动文档?

在ASP.NET Web API项目中,我们可以创建“ 帮助页面”,该页面会自动为项目中的所有Web API生成文档。

我们可以对SignalR做同样的事情吗?

asp.net signalr asp.net-web-api signalr-2

5
推荐指数
0
解决办法
98
查看次数

强制清除浏览器缓存

部署新版本的 ASP.NET 网站后,是否有办法强制客户端浏览器刷新缓存项,尤其是图像、CSS 和 Javascript 文件?

\n\n

问题是我不能\xe2\x80\x99 到处告诉每个使用该网站的人点击CTRL+ F5。我怎样才能强制浏览器这样做?

\n

asp.net asp.net-mvc

5
推荐指数
1
解决办法
3704
查看次数

System.IdentityModel.Tokens 和 Microsoft.IdentityModel.Tokens 有什么区别?我应该在 ASP.NET Core 应用程序中使用哪一个?

我们可以在 NuGet 库中找到两个独立的包:

两者似乎都定期更新并有数百万次下载。

我知道它System.IdentityModel.Tokens.Jwt依赖于Microsoft.IdentityModel.Tokens,但我不知道应该在我的 ASP.NET Core 2.0 应用程序中使用哪个。

我现在正在使用Microsoft.IdentityModel.Tokens,它足以创建 JWT 令牌并验证它们。

我需要添加System.IdentityModel.Tokens.Jwt到我的项目中并更改任何代码吗?

PS:我在这个项目中没有使用 Azure 服务。

jwt asp.net-identity-3 asp.net-core asp.net-core-2.0

5
推荐指数
1
解决办法
4712
查看次数

Azure DevOps生成错误:无法找到程序集“ System.ComponentModel.Annotations”

我有一个参考的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

3
推荐指数
1
解决办法
1349
查看次数

在ASP.NET Core的URL查询中使用破折号

我们可以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)

(以上代码无效)

asp.net-core-mvc asp.net-core asp.net-core-2.1

2
推荐指数
1
解决办法
888
查看次数

对在同一对象上调用另一个公共函数的函数进行单元测试的正确方法是什么?

虽然我知道这个问题/答案(单元测试一种调用另一种方法的方法),但仍然不确定什么是对同一类调用另一个公共方法的方法进行单元测试的最佳方法?

我做了一个示例代码(也可以在这里看到: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)

c# unit-testing design-patterns

1
推荐指数
1
解决办法
145
查看次数