在头文件中设置If-Match C#

时间:2017-10-31 04:41:53

标签: c# asp.net-web-api http-headers odata

我有Odata服务,为了执行PUT,我们需要设置标题If-Match: * In Post man我在下面给出它并且它有效

enter image description here

如何在Odata服务调用中设置此If-Match以执行PUT操作。我尝试了以下

 private async Task<HttpResponseMessage> PutJsonAsync(string messageBody,string B_Code)
 {
 string userName = ConfigurationManager.AppSettings["Username"];
 string password = ConfigurationManager.AppSettings["Password"];
 string BaseURL = ConfigurationManager.AppSettings["BaseURL"];

  try
 {
   using (var httpClient = new HttpClient())
  {
   var request = new StringContent(messageBody, Encoding.UTF8, "application/json");
   string apiUrl = "SAM('" + B_Code + "')";
   request.Headers.ContentType = new MediaTypeHeaderValue("application/json");
   request.Headers.TryAddWithoutValidation("If-Match", "*");
   var url = string.Format("{0}{1}", BaseURL, apiUrl);
   var creds = userName + ":" + password;
   var credentials = Encoding.ASCII.GetBytes(creds);
   httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));

   response = await httpClient.PutAsync(new Uri(url), request);
 }
}
catch (Exception ex)
{
 throw ex;
  }
   return response;
  }

但它不起作用并抛出错误501:Not Implemented

`response {StatusCode:501,ReasonPhrase:'Not Implemented',Version:1.1,Content:System.Net.Http.StreamContent,Headers:

OData-Version:4.0   日期:2017年10月30日星期一20:42:28 GMT   Set-Cookie:JSESSIONID = XYZ;路径= /;安全;仅Http   Set-Cookie:XYZ; PATH = /; SECURE; HTTPONLY   服务器:Apache-Coyote / 1.1   变化:接受编码   连接:保持活力   内容长度:277   Content-Type:application / json; odata.metadata =最小 System.Net.Http.HttpResponseMessage`

1 个答案:

答案 0 :(得分:3)

您的&#34;请求&#34; object,是您的内容对象,而不是HttpRequestMessage对象。我怎么意识到这一点? HttpRequestMessage上没有ContentType。

If-Match不是内容级标题(我不知道微软为什么会这样区分)。您无法在此处添加,您必须将其添加到请求标头中。如果将其添加到内容对象,则会被忽略。

这样的事情应该有效:

string apiUrl = "SAM('" + B_Code + "')";
var url = string.Format("{0}{1}", BaseURL, apiUrl);
var creds = userName + ":" + password;
var credentials = Encoding.ASCII.GetBytes(creds);
var request = new HttpRequestMessage(HttpMethod.Put, new Uri(url));
request.Content = new StringContent(messageBody, Encoding.UTF8, "application/json");
request.Headers.TryAddWithoutValidation("If-Match", "*");
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));

response = await httpClient.SendAsync(request);