gpt4 book ai didi

c# - MVC 5 身份验证和 HttpClient 没有可用的 MediaTypeFormatter

转载 作者:太空狗 更新时间:2023-10-29 23:46:01 25 4
gpt4 key购买 nike

我有一个 MVC 5 Web Api 和一个连接到它的桌面应用程序。

我有一个 Controller 并从应用程序连接到它没有任何问题,但是当我将 [Authorize] 属性放入 Controller 时,桌面应用程序中的 httpclient停止工作并说没有可用的 MediaTypeFormatter。

我认为 HttpClient 工作正常,我尝试使用请求 header 定义身份验证:httpClient.DefaultRequestHeaders.Authorization并使用这种方式 httpclient = new HttpClient(new HttpClientHandler { Credentials = new NetworkCredential("UserName", "password") });

在使用 MVC 4 的传递中,它与身份验证一起使用。

在这种情况下,使用 MVC 5,它在使用 Anonymous 时完美运行,但是当我进行身份验证时,我在 httpresponse.Content.ReadAsAsync

中得到了这个异常
No MediaTypeFormatter is available to read an object of type 'Dictionary`2' from content with media type 'text/html'.

我应该在哪里看到?

更新

我将 httpResponse 读取为一个字符串,以查看 httpclient 正在获取什么,并在该字符串中读取登录页面的 HTML。显然身份验证失败,MVC + API 重定向到登录页面。我现在应该怎么做?为什么身份验证不像以前的 MVC 4 Web API 那样工作?是因为新的OWIN认证?

最佳答案

这些问题是因为身份验证不起作用。 MVC5 使用 Web Forms 身份验证,所以我不得不创建一种新的方法来对 HttpClient 进行身份验证。

  • 获取/Account/Login 页面并读取 _RequestVerificationToken
  • 将用户名、密码和_RequestVerificationToken 发布到/Account/Login

错误是因为当身份验证失败时,MVC5 将 HttpClient 重定向到登录页面。所以我得到的不是 JSON,而是 HTML。登录页面的 HTML。

关于c# - MVC 5 身份验证和 HttpClient 没有可用的 MediaTypeFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20690765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com