从ASP.Net Web Api获取数据时获取403状态

时间:2017-09-02 08:08:56

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

我从xamarin表单中获取WEB.API。在.Net 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”此网址直接从浏览器和邮递员运行,则会提供正确的输出。

1 个答案:

答案 0 :(得分: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();
            }
        }
    }
}