下面是运行Azure函数所需的代码。它看起来很长而且凌乱。无论如何,我可以将其缩短吗?我还不熟练C#。主要问题在于第一个参数。
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
// Implementation omitted
}
答案 0 :(得分:0)
@ASKYous,
这已经是模板默认随附的重构代码。
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
// Implementation omitted
}
只有2个参数:
如果不需要授权部分,可以使用以下类似内容:
使用System.Net; 使用Microsoft.AspNetCore.Mvc; 使用Microsoft.Extensions.Primitives; 使用Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
还可以绑定到自定义对象,而不是HttpRequest。从请求的主体创建此对象,并将其解析为JSON。同样,可以将类型与200状态代码一起传递给HTTP响应输出绑定并作为响应正文返回。
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public static string Run(Person person, ILogger log)
{
return person.Name != null
? (ActionResult)new OkObjectResult($"Hello, {person.Name}")
: new BadRequestObjectResult("Please pass an instance of Person.");
}
public class Person {
public string Name {get; set;}
}