Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Authentication and HttpClient No MediaTypeFormatter is available

I have a MVC 5 Web Api and a desktop app that connects to it.

I have a controller and connect to it from the app without any issue, but when I put the [Authorize] attribute in the controller, the httpclient in desktop app stops working and says that there is not MediaTypeFormatter available.

I think the HttpClient is working fine, I tried defining authentication using the request header: httpClient.DefaultRequestHeaders.Authorization and using this way httpclient = new HttpClient(new HttpClientHandler { Credentials = new NetworkCredential("UserName", "password") });.

In the pass using MVC 4 it works with authentication.

In this case, wit MVC 5, it works perfectly when using Anonymous, but when I authenticate I get this exception in the httpresponse.Content.ReadAsAsync

No MediaTypeFormatter is available to read an object of type 'Dictionary`2' from content with media type 'text/html'.

Where should I see?

Update

I read the httpResponse as a string, to see what the httpclient is getting and I in the string the HTML of the login page. Aparently the authentication fails and the MVC + API redirects to the login page. What should I do now? Why the authentication doesnt work like in the previous MVC 4 web API? Is because the new OWIN authentication?

like image 999
Ricardo Polo Jaramillo Avatar asked Nov 11 '22 16:11

Ricardo Polo Jaramillo


1 Answers

These issue was because the authentication was not working. MVC5 use Web Forms authentication, so I had to cread a new way to authenticate the HttpClient.

  • Make a Get to the /Account/Login page and read the _RequestVerificationToken
  • Post to /Account/Login the UserName, Password, and _RequestVerificationToken

The error was because, when authentication fails, MVC5 redirects the HttpClient to the Login Page. So I was not getting JSON, I was getting HTML. The HTML of the Login Page.

like image 85
Ricardo Polo Jaramillo Avatar answered Nov 14 '22 21:11

Ricardo Polo Jaramillo