C# 生成泛型体方法
我正在写一个Web Api。我已经厌倦了总是检查模型是否有效,总是采用带有C# 生成泛型体方法,c#,.net,asp.net-web-api,C#,.net,Asp.net Web Api,我正在写一个Web Api。我已经厌倦了总是检查模型是否有效,总是采用带有try和catch子句的方法。出于这个原因,我写了一个方法Try,就是这样做的。它是异步工作的 下面是有效的代码: [Route("account/[controller]")] public class LoginController : Controller { private static async Task<Status> Try(ModelStateDictionary modelState
try
和catch
子句的方法。出于这个原因,我写了一个方法Try
,就是这样做的。它是异步工作的
下面是有效的代码:
[Route("account/[controller]")]
public class LoginController : Controller
{
private static async Task<Status> Try(ModelStateDictionary modelState, Func<Task<Status>> func)
{
try
{
return modelState.IsValid ? await func() : Status.InvalidFormat;
}
catch
{
return Status.InvalidFormat;
}
}
[HttpPost]
public async Task<Status> Login(AccountLoginModel model)
=> await Try(ModelState, async () =>
{
// yaaay! i'm safe! the model is valid!
// and if something bad happens, an exception will be caught!!
// now let's do something...
return await Task.FromResult(Status.OK);
});
}
您可以使用验证过滤器并注册过滤器,以便随时检查模型验证,如下所示:
public class ValidationFilter : ActionFilterAttribute
{
/// <summary>
/// Occurs before the action method is invoked.
/// </summary>
/// <param name="actionContext">The action context.</param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext
.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
config.Filters.Add(validationFilter);
您是否尝试过使用过滤器而不是此函数?另外,在asp.net中使用通用错误系统将消除到处都有try/catch块的需要。它需要在.net 5下进行一些调整,但最终还是可以工作的。无论如何,谢谢你。@Randolph你在.NET5中有什么不同之处?
public class ValidationFilter : ActionFilterAttribute
{
/// <summary>
/// Occurs before the action method is invoked.
/// </summary>
/// <param name="actionContext">The action context.</param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext
.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
config.Filters.Add(validationFilter);