如何检查GET请求的请求参数是否有效? C#

时间:2018-09-27 12:19:22

标签: c# asp.net-core

我想检查GET请求(这是GET请求)中是否仅提供了客户ID,而没有其他参数。在当前情况下应该如何检查?我应该返回哪个例外?

.wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

2 个答案:

答案 0 :(得分:1)

使用asp.net core 2.1我会这样做...

public class CustomerListResponse {
    public List<YourCustomerClassName> Customers {get;set;}
}

public ActionResult<CustomerListResponse> GetStatus(GetStatusRequest request)
{
    // check request
    if(doyourcheckhere == false) {
        return BadRequest();
    }

    // load your data here. Do not think in JArray and JObject
    // simply use POCOs
    var customers = GetCustomers(request.CustomerId);

    // if you need to reformat, create separate class and use e.g. automapper

    return new CustomerListResponse {
        Customers = customers
    };
}

答案 1 :(得分:0)

您可以尝试以下方法:

    [HttpGet]
    public HttpResponseMessage GetStatus(GetStatusRequest request)
    {
       try
       {
          if (request.CustomerId>0 && String.IsNullOrEmpty(request.Customername) /*&& other conditions*/)
          {
             var customers = GetCustomers(request.CustomerId);

             return Request.CreateResponse(HttpStatusCode.OK, customers );
          }
          else 
          {
               return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Your custom error message here");
          }
       }
       catch (Exception ex)
       {
           return Request.CreateErrorResponse(HttpStatusCode.BadRequest, new HttpError(ex.Message));
       }
    }