PUT,POST和DELETE RestAPI出错

时间:2016-11-17 17:33:41

标签: c# web-services rest asp.net-web-api xamarin.forms

只有GET方法一直在工作,但总是会出现PUT,POST和DELETE的错误。 我尝试通过web.config以及IIS站点下更新处理程序映射。 最初我收到状态代码405的错误,因为方法不允许。当我将Handler映射更改为

  <system.webServer>
  <handlers>
   <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
   <remove name="OPTIONSVerbHandler" />
   <remove name="TRACEVerbHandler" />
   <remove name="WebDAV" />
   <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
   <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

   <remove name="ExtensionlessUrl-Integrated-4.0" />
   <add name="ExtensionlessUrl-Integrated-4.0"
       path="*."
       verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
       type="System.Web.Handlers.TransferRequestHandler"
       preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

<validation validateIntegratedModeConfiguration="false" />

<modules>
  <remove name="ApplicationInsightsWebTracking" />
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
  <remove name="WebDAVModule"/>
</modules>

开始将415的错误视为“不支持的媒体类型”。以下是我的回复

{StatusCode:415,ReasonPhrase:'Unsupported Media Type',版本:1.1,内容:System.Net.Http.StreamContent,标题: { 缓存控制:无缓存 Pragma:没有缓存 服务器:Microsoft-IIS / 8.5 X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET 日期:2016年11月17日星期四16:44:52 GMT Content-Type:application / octet-stream;字符集= utf-8的 到期:-1 内容长度:100 }}

。以下是我的APIcalls

    // PUT: api/CreditRequests/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutCreditRequest(Guid id, CreditRequest creditRequest)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != creditRequest.CreditRequestId)
        {
            return BadRequest();
        }

        db.Entry(creditRequest).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CreditRequestExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/CreditRequests
    [ResponseType(typeof(CreditRequest))]
    public IHttpActionResult PostCreditRequest(CreditRequest creditRequest)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.CreditRequests.Add(creditRequest);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateException)
        {
            if (CreditRequestExists(creditRequest.CreditRequestId))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = creditRequest.CreditRequestId }, creditRequest);
    }

    // DELETE: api/CreditRequests/5
    [ResponseType(typeof(CreditRequest))]
    public IHttpActionResult DeleteCreditRequest(Guid id)
    {
        CreditRequest creditRequest = db.CreditRequests.Find(id);
        if (creditRequest == null)
        {
            return NotFound();
        }

        db.CreditRequests.Remove(creditRequest);
        db.SaveChanges();

        return Ok(creditRequest);
    }

我正在使用HttpClient对象调用它们。代码为

  string jsondata = JsonConvert.SerializeObject(item);
            var content = new StringContent(jsondata, System.Text.Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;
            using (var client = GetFormattedHttpClient())// Adding basic authentication in HttpClientObject before using it.
            {
              if (IsNew == true)
                    response = client.PostAsync (_webUri, content).Result;
                else if (IsNew == false)
                    response = client.PutAsync(_webUri, content).Result;

            }
            if (!response.IsSuccessStatusCode)
                               return false;
            else
            return true;

1 个答案:

答案 0 :(得分:0)

这适合我。

protected async Task<String> connect(String URL,WSMethod method,StringContent body)
{
        try
        {

            HttpClient client = new HttpClient
            {
                Timeout = TimeSpan.FromSeconds(Variables.SERVERWAITINGTIME)
            };
            if (await controller.getIsInternetAccessAvailable())
            {
                if (Variables.CURRENTUSER != null)
                {
                    var authData = String.Format("{0}:{1}:{2}", Variables.CURRENTUSER.Login, Variables.CURRENTUSER.Mdp, Variables.TOKEN);
                    var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
                }

                HttpResponseMessage response = null;
                if (method == WSMethod.PUT)
                    response = await client.PutAsync(URL, body);
                else if (method == WSMethod.POST)
                    response = await client.PostAsync(URL, body);
                else
                    response = await client.GetAsync(URL);

                ....
}