我是 Azure Functions 新手,请帮忙!
我的 WebAPI 中有以下代码来验证传递的每个参数并为每个参数抛出相应的错误。甚至在控件进入控制器之前就会引发错误,我希望在我的 Azure 函数中出现类似的内容。
下面是WebAPI代码。
启动.cs
public void ConfigureServices(IServiceCollection services)
{
//other code here
services.AddMvc()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = actionContext =>
{
return this.CustomErrorResponse(actionContext);
};
});
//other code here
}
private BadRequestObjectResult CustomErrorResponse(ActionContext actionContext)
{
////BadRequestObjectResult is class found Microsoft.AspNetCore.Mvc and is inherited from ObjectResult.
return new BadRequestObjectResult(actionContext.ModelState
.Where(modelError => modelError.Value.Errors.Count > 0)
.Select(modelError => new Error
{
ErrorField = modelError.Key,
StatusCode = 400,
ErrorDescription = modelError.Value.Errors.FirstOrDefault().ErrorMessage
}).ToList());
}
我尝试在Azure Functions中使用相同的代码,但它不起作用,似乎ConfigureApibehaviorOptions甚至没有触发。我尝试在 google 上搜索了很多 StackOverFlow 但没有找到合适的答案,因此提出了这个问题。
我应该为此使用任何自定义过滤器吗?如果是,具体如何?
services.AddMvc().ConfigureApiBehaviorOptions 的 Azure Functions 等效项是什么?如果不存在,必须采取什么方法?
我确实同意@Nate1zn,在azure函数中没有这样的选项,但您可以验证并创建自定义响应,如下所示:
using System.ComponentModel.DataAnnotations;
using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace FunctionApp111
{
public class Function1
{
private readonly ILogger _logger;
public Function1(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<Function1>();
}
[Function("Function1")]
public async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
{
if (req.Body == null || req.Body.Length == 0)
{
var response = req.CreateResponse(HttpStatusCode.BadRequest);
response.WriteString("Hello Rithwik, Request body is required !!!");
return response;
}
string rithrequest = await new StreamReader(req.Body).ReadToEndAsync();
RithwikModel con = JsonConvert.DeserializeObject<RithwikModel>(rithrequest);
var rithresults = new List<ValidationResult>();
var context = new ValidationContext(con, null, null);
if (!Validator.TryValidateObject(con, context, rithresults, true))
{
;
var response1 = req.CreateResponse(HttpStatusCode.NotFound);
var ritherror = new { ErrorField = "queryParameter", StatusCode = 400, ErrorDescription = rithresults };
var x = JsonConvert.SerializeObject(ritherror);
response1.WriteString(x);
return response1;
}
_logger.LogInformation("C# HTTP trigger function processed a request.");
var response2 = req.CreateResponse(HttpStatusCode.OK);
response2.Headers.Add("Content-Type", "text/plain; charset=utf-8");
response2.WriteString("Welcome to Azure Functions!");
return response2;
}
}
public class RithwikModel
{
[Required(ErrorMessage = "Parameter Id is required")]
public string Id { get; set; }
}
}
Output:
如果身体不正确:
如果给出正确的参数: