POST请求在REST服务中为空

时间:2015-12-28 11:23:04

标签: c# wcf rest http

我已经尝试将自己的REST服务作为WCF服务,但是当我尝试从客户端POST服务时遇到问题。

以下是服务代码:

[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";
    }
}

以下是客户端代码:

    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.

POST调用AddBook方法,但HttpRequestMessage对象始终为空:

enter image description here

我现在已经研究了几个小时,但我无法想出另一个相对简单的解决方案。 任何善良的灵魂都可以帮助我找出我所缺少的东西?

编辑:Web.Config代码:

<?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>

1 个答案:

答案 0 :(得分:0)

这个答案奏效了。 我已经尝试了类似的东西,但我一定错过了一些东西。

https://stackoverflow.com/a/6836030/4063668

我最终在我的界面中声明了这个声明:

[OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "AddBook/", BodyStyle = WebMessageBodyStyle.Bare)]
        string AddBook(Book request);
相关问题