【问题标题】:IsSuccessStatusCode is FALSEIsSuccessStatusCode 为 FALSE
【发布时间】:2017-08-13 19:25:34
【问题描述】:

请看下面的客户端代码:

namespace ReleaseLearning.Controllers
{
    public class CreateEmployeeController : Controller
    {
        //
        // GET: /CreateEmployee/

        HttpClientHandler handler = new HttpClientHandler()
        {
            UseDefaultCredentials = true
        };

        string uri = "http://localhost:52929/";


        public ActionResult CreateEmployee()
        {
            //http://localhost:52929/CreateEmployee/CreateEmployee
            //Employee Objemployee = new Employee();
            HttpClient client = new HttpClient(handler); //It will not authenticate if you remove handler (authorize attribute on server side)

            client.BaseAddress = new Uri(uri);
            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("api/Values").Result;
            if (response.IsSuccessStatusCode)
            {
                var EmployeeDetails = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result;
            }
            //return View(objEmployee);
            return View();
        }
} }

以及下面的服务器端代码:

[HttpGet]


         [Authorize]
            public List<Employee> GetemployeeList()
            {
                string username = System.Environment.UserName;

                List<Employee> Employee = new List<Employee>{
    new Employee{Employee_ID=123,Employee_Name="Saurabh Sri"},
    new Employee{Employee_ID=1567,Employee_Name="Samir Saxena"},
    };
                return Employee;
            }

我在连接到域的 PC 上的 Visual Studio 中运行此代码,它按预期工作,即response.IsSuccessStatusCode 为真。但是,如果我在连接到工作组(而不是域)的 PC 上的 Visual Studio 中运行它,那么 response.IsSuccessStatusCode 是错误的。为什么是假的?

【问题讨论】:

  • 对其余服务进行任何身份验证?
  • System.Environment.UserName 在这两种情况下给您的结果是否相同?
  • @Dijkgraaf,我在 Visual Studio 2013 中运行它,并且我已将 Windows 身份验证设置为:在 Visual Studio 中启用。
  • @Dijkgraaf ,是的。它剥离了域名和工作组名称。
  • @w0051977 试试System.Environment.UserDomainName 这个东西,看看你在这两种情况下是否得到相同的结果。

标签: c# rest authentication asp.net-web-api


【解决方案1】:

从不在域中的机器(例如在工作组中)连接时,您的调用者/API 无法使用 Windows 身份验证。

您必须更改调用方和 API 才能使用其他身份验证方法。如果在 IIS 服务器上设置本地用户,则需要使用基本身份验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2020-09-21
    • 2015-03-22
    • 2015-03-15
    • 1970-01-01
    • 2015-09-30
    相关资源
    最近更新 更多