【问题标题】:Getting 403 status while fetching data from ASP.Net Web Api从 ASP.Net Web Api 获取数据时获取 403 状态
【发布时间】:2017-09-02 08:08:56
【问题描述】:

我正在从 .Net Web API 中创建的 xamarin 表单 application.Web API 获取 WEB.API。但我收到错误

{StatusCode: 403, ReasonPhrase: 'ModSecurity Action', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
X-Powered-By-Plesk: PleskWin
Date: Sat, 02 Sep 2017 07:59:38 GMT
Content-Type: text/html
Content-Length: 2684
}}

相同的 URL 也从浏览器和邮递员提供正确的输出。 我正在使用下面的代码来获取 web api。我不知道到底发生了什么。

string RestUrl = "http://msystemtest.msystem.co/api/Users?userId={0}&pass={1}";

            var uri = new Uri(string.Format(RestUrl, uid, pass));
            string resp = string.Empty;

            var response = await client.GetAsync(uri);

            string statHold = string.Empty;
            if(response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                 resp = JsonConvert.DeserializeObject<string>(content);
            }

如果“http://msystemtest.msystem.co/api/Users?userId=test&pass=1”这个 URL 直接从浏览器和邮递员运行,它会给出正确的输出。

【问题讨论】:

  • 您检查过uri 结果吗?可能格式输入参数错误
  • 格式正确。我已经直接测试了URI结果。它工作正常。

标签: c# asp.net-mvc xamarin asp.net-web-api


【解决方案1】:

似乎服务器不喜欢您从非浏览器中阅读此内容。下面是从控制台应用程序模拟浏览器的代码:

using System;
using System.Net.Http;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");

                var response = httpClient.GetAsync("http://msystemtest.msystem.co/api/Users?userId=test&pass=1").Result;
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                Console.ReadKey();
            }
        }
    }
}

【讨论】:

  • 它在控制台应用程序中运行良好。但是当我尝试从 Xamarin Forms 应用程序实现时,它给出了相同的状态。
  • 尝试使用 fiddler 检查 Xamarin Forms 应用程序是否不会覆盖用户代理标题
  • 通过对代码进行细微的更改,它可以正常工作。感谢您的协助。
猜你喜欢
  • 2012-08-29
  • 2018-03-29
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2018-03-18
相关资源
最近更新 更多