我已经将自己的rest服务作为wcf服务进行了试验,但是当我试图从客户机发送到该服务时遇到了问题。
以下是服务代码:

[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对象始终为空:
c# - REST服务中的POST请求为空-LMLPHP
我已经研究了好几个小时了,但是我不能想出另一个相对简单的解决方案。
有什么善良的灵魂可以帮助我找出我所缺少的吗?
编辑: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>

最佳答案

这个答案起了作用。
我已经试过类似的东西了,但一定是一路上漏掉了什么。
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);

关于c# - REST服务中的POST请求为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34492597/

10-17 02:16