我正在使用MVC4应用程序并使用WebAPI来获取/发送我的所有数据.在控制器中,我使用HttpClient请求来获取数据,并且一切正常.我面临的问题是,当在项目中启用Windows身份验证时,Web API调用将返回401 Unauthorized错误.
我的控制器中执行调用的代码是:
using (var client = new HttpClient())
{
var invoiceDetailUrl = BASE_URL + Url.HttpRouteUrl(
"DefaultApi",
new { controller = "InvoiceDetails", id = id }
);
var result = client.GetAsync(invoiceDetailUrl).Result;
}
Run Code Online (Sandbox Code Playgroud)
必须为站点启用Windows身份验证,但不一定是Web API控制器.我试过在web.config中排除API控制器,如下所示:
<location path="api">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
Run Code Online (Sandbox Code Playgroud)
但web.config的添加没有做任何事情.
有什么建议?
我一直在寻找升级当前MVC 4应用程序的解决方案,我必须使用新的MVC 5二进制文件.我无法在任何地方找到解决方案.
有人有主意吗?
我有一个方法,我为简化使用HttpClient调用而创建.它使用方法HttpReponse.Content.ReadAsAsync().结果从API获取响应.
一切正常.我的方法看起来像这样:
public static T ExecuteAPIGetRequest<T>(string url, Dictionary<string, string> parameters)
{
HttpClient client = new HttpClient();
//basic authentication
var t = new object();
string baseURL = "myurl";
//Execute request
HttpResponseMessage response = client.GetAsync(baseURL).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<T>().Result;
}
else
{
return (T)t;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果查询失败,它需要返回一个空类型的T.如果它是我编写的自定义类,这很好,但它不适用于像string或string []这样的对象.有任何想法吗?
干杯
大斑病