【问题标题】:404 File not found exception when calling ASP.NET webapi调用 ASP.NET webapi 时找不到 404 文件异常
【发布时间】:2020-05-12 05:36:39
【问题描述】:

当我尝试将参数从 android 发布到 asp.net web api 时,我得到了 file not found 异常。但是同样的 web api 正在与邮递员一起工作。请建议我应该在哪一部分更正?

Android 代码是:

 public String CallWebAPI()
       {

    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new FormBody.Builder()
            .add("name", "Rahul")
           .build();

    Request request = new Request.Builder()
            .url("http://www.xxxx.co/testapi/TestNameWEBApi")
            .post(formBody)
            .build();

    Call call = client.newCall(request);
           Response response = null;
           try {

               response = call.execute();
               Log.e("ATTEST", "App1 Error is :" + response.toString());

           } catch (IOException e) {
               Log.e("ATTEST", "App1 IOException is :" + e.toString());

               e.printStackTrace();
           }
           return response.toString();
}

而 webAPI 是:

   [RoutePrefix("testapi")]

    [Route("TestNameWEBApi"), HttpPost]
    public HttpResponseMessage TestNameWEBApi(string name)
    {
        try
        {
            var Response = name;
            var Result = this.Request.CreateResponse(HttpStatusCode.OK, Response, new JsonMediaTypeFormatter());
            return Result;//return same parameter to check if the value is reaching here or not
        }
        catch (Exception ex)
        { 
            HttpError Error = new HttpError(ex.Message) { { "IsSuccess", false } };
            return this.Request.CreateErrorResponse(HttpStatusCode.OK, Error);
        }
    }

【问题讨论】:

  • 你的控制器上有路由吗?
  • yes RoutePrefix 设置为 testapi
  • 检查你的类是否继承 Controller 或者 webApi 是否继承自 ApiController

标签: android asp.net post asp.net-web-api http-status-code-404


【解决方案1】:

您的请求缺少查询参数名称

RequestBody formBody = new FormBody.Builder()
    .add("name", "Rahul")
    .build();

上面的代码将名称和数据添加到正文,而不是 URL。

您可能会收到 404 Not Found,因为您的服务器需要提供 name 参数,否则它将与完整路由不匹配。

从正文中删除名称和数据,然后将它们添加到 URL。

 public String CallWebAPI() {

 OkHttpClient client = new OkHttpClient();
 RequestBody formBody = new FormBody.Builder()
     .build();

 Request request = new Request.Builder()
     .url("http://www.xxxx.co/testapi/TestNameWEBApi?name=Rahul")
     .post(formBody)
     .build();

 Call call = client.newCall(request);
 Response response = null;
 try {

     response = call.execute();
     Log.e("ATTEST", "App1 Error is :" + response.toString());

 } catch (IOException e) {
     Log.e("ATTEST", "App1 IOException is :" + e.toString());

     e.printStackTrace();
 }
 return response.toString();
}

在这种情况下,body 完全是空的,但你可以在路由工作后添加到它。

可能有更好的方法将查询参数添加到 URL,但这应该可行。

【讨论】:

  • 我也使用了 [FromBody] 来强制方法读取请求正文,并使用模型来获取客户端传递的值。该方法自动从请求中获取值并将它们设置到模型中,这非常容易。
猜你喜欢
  • 2011-06-11
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多