繁体   English   中英

如何从前端 React.js 处理 ASP.NET 核心 web API 中的“未定义”或“空”?

[英]How to handle "undefined" or "null" in ASP.NET Core web API from frontend React.js?

我正在编写 ASP.NET 核心 REST API。这里是 controller 方法,当传入路由匹配时应该选择此方法。

controller.cs

[HttpGet]
        [Route("/api/Account/{accountID}/{productIds}/files")]
        public ActionResult<IEnumerable<FilesDto>> GetFiles(long accountID, string productIds)
        {
            using (new MethodCallLogger(logger, UserContext))
            {
                return Ok(FilesService.GetFiles(accountID, productIds));
            }
        }

文件服务.cs

public IEnumerable<FilesDto> GetFiles(long accountID, string productIds)
{
// in some cases productIds will come empty

if(!string.isNullorEmpty(productIds)
{

}
}

在某些情况下,productIds 会变空,变成 select 所有产品。

如果我从 FrontEnd Reactjs 传递 null 或空字符串,这里它接收“null”或“undefined”作为字符串值。 因此 string.isNullorEmpty 条件得到通过并抛出错误,如无效的 produtID。

那么,什么是处理这个“null”或“undefined”的完美方法。 或者我们如何将空字符串或 null 从 reactjs 传递到后端。

谢谢你的时间。

创建一个NotFoundApiException

public class NotFoundApiException : Exception
{
    public NotFoundApiException(string message) : base(message) { }

    public NotFoundApiException(string message, params object[] args)
        : base(String.Format(CultureInfo.CurrentCulture, message, args))
    {
    }
}

创建自定义错误处理中间件

public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception error)
        {
            var response = context.Response;
            response.ContentType = "application/json";
            
            string erorMessage = error.Message;

            switch (error)
            {

                case NotFoundApiException e:
                    // custom not-found application error
                    errorMessage = e.Message;
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    break;

                default:
                    // unhandled error
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
            }

            var result = JsonConvert.SerializeObject(new
            {
                message = errorMessage
            });

            await response.WriteAsync(result);
        }
    }
}

然后使用 Startup/Program.cs 中的中间件:

app.UseMiddleware<ErrorHandlerMiddleware>();

然后在值为 null 时简单地抛出这个异常:


if(value is null)
    throw new NotFoundApiException("Data is null")

例如,您可以在productIds中使用“all”:

/api/账户/55/所有/文件

或者您也可以更改 api 的结构,例如:

/api/账户/文件/{accountID}/{productIds}

并且productIds可以是“all”Number

或者您可以对productIds使用 queryParams,例如:

/api/Account/{accountID}/files?productIds=编号

例如:

/api/Account/20/files?productIds=4

当未发送productIds时,您发送特定 accountID 的所有文件

1./api/账户/20/文件

或者

2./api/Account/20/files?productIds=all

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM