将请求发送到服务器ASP.NET Web Api时出现错误403

时间:2016-03-17 19:58:40

标签: android-studio asp.net-web-api

我使用ASP.NET Web API Web服务器进行Android客户授权。我输入我的登录名,按回车键,找到用户找到的答案。但它只能通过android模拟器。当我尝试使用真实设备时,路由器上的错误403端口也会在您的计算机上打开。电话和计算机在同一网络上。如果您驾驶计算机和端口(192.168.0.101:7899),则在您的手机浏览器中打开该服务器上的页面。这是对服务器的请求:

@GET("/login")
void findLogin(@Query("login") String login, Callback<Users> callback);

该连接代码:

 public class RestClient {
       private UploadService  uploadService;
       private String URL ="http://192.168.0.101:7899/api/";       
       public RestClient(){
             Gson localGson = new GsonBuilder().create();
             this.uploadService = ((UploadService)new RestAdapter.Builder()
                 .setEndpoint(URL)
                 .setConverter(new GsonConverter(localGson))
                 .setRequestInterceptor(new RequestInterceptor() {
                            public void intercept(RequestFacade requestFacade) {
                                if (URL.contains("192.168.0.101")) {                             
                                    requestFacade.addHeader("Host", localhost");
                                }
                            }
                        })
                .build().create(UploadService.class));    
        }

如何解决403错误的问题? 抱歉我的英文不好

1 个答案:

答案 0 :(得分:1)

假设您遇到问题CORS

因此,首先我们需要使用NuGet Package Manager导入这些包。单击工具&gt;打开包管理器控制台。 NuGET包管理器&gt;在Package Manager控制台中,您只需输入以下命令:

  

安装包Microsoft.AspNet.WebApi.Cors -IncludePrerelease

现在,在解决方案资源管理器中,转到App_Start&gt; WebApiConfig.cs 在Register(...)方法中添加以下行:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Re‌​ferenceLoopHandling = ReferenceLoopHandling.Ignore;

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

因此,您的WebApiConfig.cs看起来像:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Student_Management_System
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Re‌​ferenceLoopHandling = ReferenceLoopHandling.Ignore;
            // Web API configuration and services
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
        }
    }
}

您可能想参考我的博客:https://programmingwithease.wordpress.com/2014/06/18/learning-asp-net-web-api-2-using-c/

相关问题