【发布时间】: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