【问题标题】:Web-Api 400 BadRequest when search parameter is blank搜索参数为空时的 Web-Api 400 BadRequest
【发布时间】:2013-08-24 06:35:04
【问题描述】:

我正在使用带有 mvc4 的 web-api

我正在制作搜索功能,在某些情况下,如果我过滤数据然后删除该文本框值然后按搜索按钮,则需要显示整个列表,但在我的情况下显示 400 错误请求。由于搜索参数为空,我知道如果搜索参数为空,那么它会在 web-api 中抛出 400 错误。

任何人有适当的解决方案,请告诉我。

data: "CurrPage=" + JsCurrPage + "&PageSize=" + parseInt(pagesize) + "&BuildTypeName=" + $("#BuildTypeName").val(),

这里在某些情况下 BuildType 是空白的。搜索时

//控制器

public HttpResponseMessage GetBuildTypeList(int CurrPage, int PageSize, string BuildTypeName)
        {

        }

Net -> XHR URL 是:

http://{parentURL}/api/BuildTypeWebApi/GetBuildTypeList?CurrPage=1&PageSize=10&BuildTypeName=

【问题讨论】:

  • 发布400的内容
  • 是什么意思?当我的字符串 BuildTypeName 为 null 时,它会抛出异常 400 错误
  • @tom : 我的帖子更新了
  • 把你所有的代码贴出来,太难理解你在问什么

标签: asp.net-mvc-4 asp.net-web-api http-status-code-400


【解决方案1】:
public HttpResponseMessage GetBuildTypeList(string BuildTypeName, int CurrPage = 1, int PageSize = 0)

在您的业务逻辑中,您可以假设 PageSize 为 0 表示所有记录。

【讨论】:

  • string BuildTypeName 正在搜索参数,如果它为 null 则出现 400 bad reuqest,我也做了类似 string BuildTypeName = null 但仍然 400 错误,等待您的响应。
  • 在 fiddler 中调用并让我们知道响应包含什么
  • 响应为 400 错误请求。
  • 为什么即使我已经定义了 web-api 方法 string BuildType="" 也无法正常工作?
  • Web api 通常足以提供有关缺失内容的信息。你应该包括那个
【解决方案2】:

如果您允许 CurrPage 和 PageSize 为空,那么您需要接受可为空的整数:

public HttpResponseMessage GetBuildTypeList(int? CurrPage, int? PageSize, string BuildTypeName)

然后,您将更新查询,以便在未提供过滤器值的情况下返回整个列表。

【讨论】:

  • string BuildTypeName 正在搜索参数,如果它为 null 则出现 400 bad reuqest,我也做了类似 string BuildTypeName = null 但仍然 400 错误,等待您的响应。
  • 您可以尝试删除“BuildTypeName”,看看您会得到什么吗? http://{parentURL}/api/BuildTypeWebApi/GetBuildTypeList?CurrPage=1&PageSize=10
  • same 400 bad reuqest 因为我的控制器方法也需要构建类型名称参数,我已经尝试过你提到的但它也抛出 400 bad request, JFI - 400 bad request only when value is blank or参数不匹配,因此解决方案需要以这种方式思考..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 2013-01-15
  • 2017-04-01
  • 1970-01-01
相关资源
最近更新 更多