我有一个带有以下控制器的ASP.NET Core,该控制器接受POST请求:
[Route("api/v1/tenants/tests")]
public class TestsController : Controller
{
[HttpPost]
public IActionResult Post(string tenantId)
{
return Ok();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经开发了一种“空”中间件来进行测试。它Configure在Startup.cs文件的方法中定义:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.Use(async (context, next) =>
{
// Forward to the next one.
await next.Invoke();
});
}
Run Code Online (Sandbox Code Playgroud)
题
当我通过Postman调用控制器时,对该POST方法的初始调用成功通过中间件,然后成功到达控制器。但是,以下调用直接转到Controller,完全跳过了中间件。这是为什么?
我有一个 Azure 函数,我想设置一个自定义 HTTP 端点。在回答这个 SO question 之后,我得到了这样的结果:
[FunctionName("DoSomething")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/tenants/{tenantId}/locations/{locationId}/products?manufacturer={manufacturer}")]
HttpRequest request, ILogger logger, string tenantId, string locationId, string manufacturer)
{
//
}
Run Code Online (Sandbox Code Playgroud)
但是,Webjob 不接受该路由:
"v1/tenants/{tenantId}/locations/{locationId}/products?manufacturer={manufacturer}"
Run Code Online (Sandbox Code Playgroud)
原因是因为问号“?”:
创建名称为“DoSomething”且模板为“api/v1/tenants/{tenantId}/locations/{locationId}/products?manufacturer={manufacturer}”的路由时出错。文字部分 'products?manufacturer=' 无效。文字部分不能包含“?” 特点。参数名称:routeTemplate 文字部分 'products?manufacturer=' 无效。文字部分不能包含“?” 特点。
题
如何在 Azure 函数的自定义 HTTP 终结点中指定查询参数?
我有一组在 .NET Core 3.1 上运行的 Azure Functions v3。
我需要指定自定义转换器,因此当我在函数中构建 a 时,System.Text.Json我提供了一个自定义实例:JsonSerializerOptionsJsonResult
return new JsonResult(<ContractClass>, NSJsonSerializerOptions.Default)
{
StatusCode = StatusCodes.Status200OK
};
Run Code Online (Sandbox Code Playgroud)
问题
我收到以下错误,并且我不确定 Newtonsoft 来自哪里,因为 ASP.NET Core 应该使用System.Text.Json:
Microsoft.AspNetCore.Mvc.NewtonsoftJson: Property 'JsonResult.SerializerSettings' must be an instance of type 'Newtonsoft.Json.JsonSerializerSettings'.
Run Code Online (Sandbox Code Playgroud)
更新
我发现该JsonResult实例正在寻找 的实现IActionResultExecutor<JsonResult>,并得到一个NewtonsoftJsonresultExecutor而不是SystemTextJsonResultExecutor。JsonResult这是的方法的代码ExecuteResultAsync:
我认为 Azure Function 将依赖于 ASP.Net Core,而 ASP.Net Core 又依赖于System.Text.Json.
我有以下程序:
async Task Main()
{
IList<int> myList = await TestAsync();
}
public Task<IList<int>> TestAsync()
{
return Task.FromResult(new List<int>());
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨它无法在方法中将Task<List>a转换为 a :Task<IList>TestAsync
CS0029 无法将类型隐式转换
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>为System.Threading.Tasks.Task<System.Collections.Generic.IList<int>>
为什么它不知道我的方法返回 IList 的任务?
我使用Azure Http Trigger创建了一个开箱即用的Azure功能应用程序.这给了我下面的代码.我所更新的是我正在将HttpRequest主体转换为我的Helper类.
这是代码
public static class TriggerTest
{
[FunctionName("TriggerTest")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = new StreamReader(req.Body).ReadToEnd();
Helper data = JsonConvert.DeserializeObject<Helper>(requestBody);
name = name ?? data?.value;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
public class Helper
{
public string value …Run Code Online (Sandbox Code Playgroud) 我构建了一个在 Azure (ASP.Net Core 2.1) 上运行的应用程序,它涉及微服务和客户端应用程序:
客户端应用程序 (Android) --calls--> 微服务 A (网关) --forwards-> 微服务 B
在微服务B 中,我在 an 中定义了以下方法Controller:
[HttpPatch]
[SwaggerOperation(OperationId = nameof(PatchEntityAsync))]
[Route(ApiConstants.Constraints.ControlId, Name = nameof(PatchEntityAsync))]
[SwaggerResponse(StatusCodes.Status204NoContent, "Result of the patch")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[Consumes(MediaTypes.Application.JsonPatch)]
public async Task PatchEntityAsync(string tenantId, Guid entityId, JsonPatchDocument<EntityModel> entityUpdates)
{
//
}
Run Code Online (Sandbox Code Playgroud)
该方法接受 aJsonPatchDocument以应用于EntityModel。生成 swagger 并运行 autorest 后,我得到以下自动生成的方法:
Task<HttpOperationResponse> PatchEntityWithHttpMessagesAsync(string tenantId, System.Guid controlId, IList<Operation> entityPatches = default(IList<Operation>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
Run Code Online (Sandbox Code Playgroud)
这个自动生成的客户端正被微服务A …
我有一个 Azure Function v3.1。
在我的机器上(macOS + Visual Studio Mac / Jetbrains Rider),它无法构建并出现以下错误:
Error : Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
Run Code Online (Sandbox Code Playgroud)
这是完整的调用堆栈:
##[error]C:\Users\VssAdministrator\.nuget\packages\microsoft.net.sdk.functions\3.0.9\build\Microsoft.NET.Sdk.Functions.Build.targets(32,5): Error : Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
at Mono.Cecil.BaseAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)
at Mono.Cecil.BaseAssemblyResolver.Resolve(AssemblyNameReference name)
at Mono.Cecil.DefaultAssemblyResolver.Resolve(AssemblyNameReference name)
at Mono.Cecil.MetadataResolver.Resolve(TypeReference type)
at Mono.Cecil.ModuleDefinition.Resolve(TypeReference type)
at Mono.Cecil.TypeReference.Resolve()
at MakeFunctionJson.AttributeExtensions.IsWebJobsAttribute(CustomAttribute attribute)
at MakeFunctionJson.ParameterInfoExtensions.<>c.<ToFunctionJsonBindings>b__1_0(CustomAttribute a)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.ToList()
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at MakeFunctionJson.ParameterInfoExtensions.ToFunctionJsonBindings(ParameterDefinition parameterInfo)
at MakeFunctionJson.MethodInfoExtensions.<>c.<ToFunctionJson>b__6_1(ParameterDefinition p)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的通用类:
public class Property<TObjectType>
{
}
Run Code Online (Sandbox Code Playgroud)
我想使用新的System.Text.Json 源生成器,但它似乎不适用于通用类。JsonSerializerContext这是该类的派生:
[JsonSerializable(typeof(Property<>))]
public partial class PropertyJsonContext<TObjectType> : JsonSerializerContext
{
}
Run Code Online (Sandbox Code Playgroud)
该错误有点奇怪,因为它使所有其他非通用JsonSerializerContext实现因这两个错误而失败:
Error CS0534: 'XXXJsonContext' does not implement inherited abstract member 'JsonSerializerContext.GeneratedSerializerOptions.get'
Error CS0534: 'XXXJsonContext' does not implement inherited abstract member 'JsonSerializerContext.GetTypeInfo(Type)'
Run Code Online (Sandbox Code Playgroud)
我认为还有一个与我的问题有关的警告:
CSC : warning CS8785: Generator 'JsonSourceGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'ArgumentException' with message 'The hintName 'PropertyJsonContext`1.NSPropertyTObjectType.g.cs' …Run Code Online (Sandbox Code Playgroud) Qt有一个简洁的功能,可以使用Lambda进行定时操作.
使用单行代码延迟后可以执行操作:
QTimer::singleShot(10, [=](){
// do some stuff
});
Run Code Online (Sandbox Code Playgroud)
虽然我没有在C#中找到相同的东西.
我得到的最接近的是
Timer timer = new Timer();
timer.Interval = 10;
timer.Elapsed += (tsender, args) => {
// do some stuff
timer.Stop();
};
timer.Start();
Run Code Online (Sandbox Code Playgroud)
但它远非(视觉上)清洁.
有没有更好的方法来实现这一目标?
用例是将串行线路上的数据发送到某些硬件,点击或按下按钮时,通常需要在几毫秒后发送命令和数据包.
具有辅助功能的解决方案:
public void DelayTask(int timeMs, Action lambda)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = timeMs;
timer.Elapsed += (tsender, args) => { lambda.Invoke(); };
timer.AutoReset = false;
timer.Start();
}
Run Code Online (Sandbox Code Playgroud)
叫做
DelayTask(10, () => /* doSomeStuff...*/ );
Run Code Online (Sandbox Code Playgroud) 我想知道的区别FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base和FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build。你能解释一下之间的区别AS base和AS build?
这是dockerfileVisual Studio 生成的默认值:
FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build
WORKDIR /src
COPY ["WebApplication1/WebApplication1.csproj", "WebApplication1/"]
RUN dotnet restore "WebApplication1/WebApplication1.csproj"
COPY . .
WORKDIR "/src/WebApplication1"
RUN dotnet build "WebApplication1.csproj" -c Release -o /app
FROM build AS publish
RUN dotnet publish "WebApplication1.csproj" -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app . …Run Code Online (Sandbox Code Playgroud) c# ×9
asp.net-core ×3
azure ×3
json.net ×2
.net ×1
.net-6.0 ×1
autorest ×1
azure-devops ×1
docker ×1
dockerfile ×1
image ×1
middleware ×1
nuget ×1
swagger ×1