2017年12月27日 星期三

Forms驗證與HttpClient

Tool:Visual Studio 2017 15.5.1版
OS:Windows 10
.NET Framework 4.6
ASP.NET Web Forms

叫用Web API驗證失敗產生的錯誤訊息

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

在ASP.NET Web Form網站中設計Web API,而在ASP.NET Web Form網站啟用Forms驗證:

<authentication mode="Forms">
  <forms loginUrl="login.aspx"></forms>
</authentication>
<authorization>
  <deny users="?"/>
</authorization>

Web API程式如下:

public class MyAPIController : ApiController {
  public string Get( ) {
    return "Hello";
  }
}


若使用HttpClient叫用Web API時,使用以下程式:

HttpClient client = new HttpClient( );
client.BaseAddress = new Uri( "http://localhost:50778/" );
HttpResponseMessage resp = client.GetAsync( "api/MyAPI" ).Result;
string data = null;
if ( resp.IsSuccessStatusCode ) {
  data = resp.Content.ReadAsAsync<string>( ).Result;
}
Response.Write( data );

就會出現錯誤訊息,這是因為驗證的關係

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

image

修改用戶端程式如下,問題就可以解決了!

HttpClient client = new HttpClient( new HttpServer( GlobalConfiguration.DefaultHandler ) );
client.BaseAddress = new Uri( "http://localhost:50778/" );
HttpResponseMessage resp = client.GetAsync( "api/MyAPI" ).Result;
string data = null;
if ( resp.IsSuccessStatusCode ) {
  data = resp.Content.ReadAsAsync<string>( ).Result;
}
Response.Write( data );

沒有留言:

總瀏覽量