I've experimented with my own REST service as a WCF service, but I am having problems when I try to POST to the service from a client.
Here is the Service code:
[ServiceContract]
public interface IBookService
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "AddBook/")]
string AddBook(HttpRequestMessage request);
}
public class BookService : IBookService
{
static IBookRepository repository = new BookRepository();
public string AddBook(HttpRequestMessage request)
{
try
{
// request is always empty.
var content = request.Content;
Book tempBook = JsonConvert.DeserializeObject<Book>(content.ReadAsStringAsync().Result);
repository.AddNewBook(tempBook);
}
catch (Exception ex)
{
//
}
return "AddBookTest";
}
}
Here is the client code:
var client = new HttpClient();
var url = new Uri("http://localhost:53258/");
client.BaseAddress = url;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var tempBook = new Book() { BookId = 10, Title = "Title", ISBN = "123143234"};
var serializedBook = JsonConvert.SerializeObject(tempBook);
HttpContent content = new StringContent(serializedBook, Encoding.UTF8, "application/json");
var postResponse = _client.PostAsync("AddBook/", content).Result;
if (!postResponse.IsSuccessStatusCode)
// Always returns 400 Bad request.
The POST calls the AddBook method, but the HttpRequestMessage object is always empty:
I've researched for hours now, yet I can't come up with another relatively simple solution. Any kind souls that can help me figure out what I am missing?
EDIT: Web.Config code:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="MyRestService.BookService" behaviorConfiguration="bookServiceBehavior">
<endpoint address=""
binding="webHttpBinding"
contract="MyRestService.IBookService"
behaviorConfiguration="RESTEndpointBehavior" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="RESTEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="bookServiceBehavior">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>