简体   繁体   English

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

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

im in the process of writing ASP.NET Core REST API. here is controller method and this method should get selected when incoming route was matched.我正在编写 ASP.NET 核心 REST API。这里是 controller 方法,当传入路由匹配时应该选择此方法。

controller.cs 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));
            }
        }

FilesService.cs文件服务.cs

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

if(!string.isNullorEmpty(productIds)
{

}
}

in some cases productIds will come empty, to select all the products.在某些情况下,productIds 会变空,变成 select 所有产品。

if i pass null or empty string from FrontEnd Reactjs, here its receiving "null" or "undefined" as string value.如果我从 FrontEnd Reactjs 传递 null 或空字符串,这里它接收“null”或“undefined”作为字符串值。 so the string.isNullorEmpty condition get passed and throwing error, like invalid produtIDs.因此 string.isNullorEmpty 条件得到通过并抛出错误,如无效的 produtID。

so, what is the perfect to handle this "null" or "undefined".那么,什么是处理这个“null”或“undefined”的完美方法。 or how can we pass empty string or null from reactjs to backend.或者我们如何将空字符串或 null 从 reactjs 传递到后端。

Thanks for your time.谢谢你的时间。

Create a NotFoundApiException创建一个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))
    {
    }
}

Create A Custom Error handling Middleware创建自定义错误处理中间件

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);
        }
    }
}

Then use the Middleware in Startup/Program.cs:然后使用 Startup/Program.cs 中的中间件:

app.UseMiddleware<ErrorHandlerMiddleware>();

Then simply throw this exception when value is null by:然后在值为 null 时简单地抛出这个异常:


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

You can use "all" in productIds for example:例如,您可以在productIds中使用“all”:

/api/Account/55/all/files /api/账户/55/所有/文件

Or you can also change the structure of the api for example:或者您也可以更改 api 的结构,例如:

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

And productIds can be "all" or Number并且productIds可以是“all”Number

or you can use queryParams for productIds like:或者您可以对productIds使用 queryParams,例如:

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

for example:例如:

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

and when productIds not sended, you send all files for specific accountID当未发送productIds时,您发送特定 accountID 的所有文件

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

Or或者

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

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

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