程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

web api

編輯:關於.NET

HttpResponseMessage 和  HttpResponseMessage

HttpResponseMessage 用於處理返回狀態信息

HttpResponseMessage 用於發生錯誤信息時  404 505

自定義返回狀態

 public HttpResponseMessage dele(int id)
         {
             return Request.CreateResponse(HttpStatusCode.OK);
         }

自定義狀態碼

 public HttpResponseMessage  dele(int id)
        {
            var resopnse = Request.CreateResponse(HttpStatusCode.OK);
            resopnse.StatusCode = HttpStatusCode.OK;
            resopnse.Content = new StringContent("狀態值返回");
            return resopnse;
        }

 

響應列舉對象

 public IEnumerable<product> Get()
        {
            List<product> lp = new List<product>()
            {
                new product() {name="xiaowang" },
                new product() {name="xiaoli" }
            };
            return lp;
        }
      
       public HttpResponseMessage dele(int id)
        {
            HttpResponseMessage  message = new HttpResponseMessage(HttpStatusCode.OK );
            message.Content = new ObjectContent<IEnumerable<product>>(Get(), new JsonMediaTypeFormatter());
            return message;
        }

CreateResponse<T> 泛型的回應方法

 public HttpResponseMessage dele(int id)
        {
            IEnumerable<product> ienu = Get();
            var pro = ienu.Where(p => p.name == "xiaowang");
            if (pro.FirstOrDefault<product>() != null)
            {
                return Request.CreateResponse<product>(HttpStatusCode.OK, pro.First<product>());
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

自定義HttpResponseException

 

   public HttpResponseMessage dele(int id)
        {
            var message = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("錯誤消息"),
                ReasonPhrase = "出錯了"
            };
            throw new HttpResponseException(message);

        }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved