wstcl 2025-02-22 12:35 采纳率: 38.1%
浏览 11

访问asp.net web 出现奇怪的bad request 400错误

用vs.net 2015写一个webapi,里面放一个“一般处理程序”,也就是ashx页面,ashx页面代码不作修改,即默认输出“Hello World”(即请求不需要任何参数),运行网站,浏览器显示“Hello World”,用postman get请求网站,也显示“Hello World”,然后用android studio的avd模拟器连接(avd模拟器如果访问本地服务器,要将ip locahost或127.0.0.1修改为10.0.2.2),出现protocol=http/1.1, code=400, message=Bad Request的错误,以前用vs.net 2010写接口,可以正确访问,于是按前面方法建立一个无修改的"一般处理程序”,然后发现是可以正确访问的,即在avd模拟器上输出“Hello World”,更神奇的是我将vs.net 2015写的webapi发布到iis,然后再avd模拟器连接,又正确显示“Hello World”了,也就是说Bad Request 400错误只在vs.net 2015开发调试模式下才出现,同样客户端和服务端代码也是没有问题的。真是奇怪。

.net 服务端代码

<%@ WebHandler Language="C#" Class="GetHandler" %>

using System;
using System.Web;
using System.Diagnostics;

public class GetHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

       
        context.Response.Write("Hello World");


    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

AS客户端代码

package person.yinzhenwei.connnetwebapidemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import person.yinzhenwei.connnetwebapidemo.util.PermessionUtil;
import swaddle.yinzhenwei.waitdialog.WaitDialog;

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    private EditText etget;
    private Button btnget;
    private TextView tvget;

    private WaitDialog waitDialog;

    private static String[] PERMISSIONS = {
            Manifest.permission.INTERNET
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PermessionUtil.CheckPermissions(this,PERMISSIONS,1);

        setContentView(R.layout.activity_main);
        etget=findViewById(R.id.ETGet);
        btnget=findViewById(R.id.BtnGet);
        tvget=findViewById(R.id.TVGet);
        waitDialog=new WaitDialog(this);

        findViewById(R.id.BtnGet).setOnClickListener(this);
    }

    private void rungetdata()
    {
        waitDialog.setText("hold");
        waitDialog.show();
        new TUpload().start();
    }

    private String Strgetdata()
    {
        String name=etget.getText().toString();
        String result="";
        String url="http://10.0.2.2:59771/GetHandler.ashx";
        OkHttpClient client = new OkHttpClient();
//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)//file
//                .build();
        Request request = new Request.Builder()
                .addHeader("Content-Type", "text/plain")
                .url(url)
                .get()
                .build();
            Log.v("lzb","fdsfsf");
        try
        {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful())
            {
                Log.v("lzb","Unexpected code "+response);
                result= "Unexpected code "+response;
                //throw new IOException("Unexpected code " + response);
            }
            else
            {
                result=response.body().string();
            }
        }
        catch (Exception ex)
        {
            result=ex.toString();
            Log.v("lzb","error"+ex.toString());
        }

        return  result;




    }






    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case (R.id.BtnGet):
                rungetdata();
                break;
        }
    }

    private class TUpload extends Thread
    {

        String text="";
        public void run()
        {

            text=Strgetdata();
            runOnUiThread(new Runnable() {

                @Override
                public void run()
                {

                  tvget.setText(text);
                  waitDialog.dismiss();

                }
            });
        }
    }
}

  • 写回答

5条回答 默认 最新

  • 阿里嘎多学长 2025-02-22 12:35
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    解决方案

    你遇到的问题可能是由于 ASP.NET 的路由机制导致的。ASP.NET 会自动将 URL 路由到对应的控制器和动作方法中,如果你没有在 Web.config 文件中配置路由规则,可能会导致请求被错误地路由到一个不存在的控制器或动作方法中,从而导致 400 错误。

    为了解决这个问题,你可以尝试以下几种方法:

    1. 在 Web.config 文件中添加路由规则,例如:
    <configuration>
      <system.webServer>
        <handlers>
          <add name="ashx" path="*.ashx" verb="*" type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" />
        </handlers>
        <rewrite>
          <rules>
            <rule name="Rewrite to ashx" stopProcessing="true">
              <match url="*.ashx" />
              <action type="Rewrite" url="ashx/{R:0}" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>
    
    1. 在 ashx 文件中添加一个 ProcessRequest 方法,例如:
    using System;
    using System.Web;
    
    public class HelloWorld : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write("Hello World");
        }
    }
    
    1. 在 Web.config 文件中添加一个 handlers 节点,例如:
    <configuration>
      <system.webServer>
        <handlers>
          <add name="HelloWorld" path="HelloWorld.ashx" verb="*" type="HelloWorld" />
        </handlers>
      </system.webServer>
    </configuration>
    

    这些方法都可以解决你遇到的问题,但是如果你想要使用默认的 ASP.NET 路由机制,你可以尝试使用第一个方法。

    评论

报告相同问题?

问题事件

  • 创建了问题 2月22日