Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.35 KB | None | 0 0
  1. public static void Register(HttpConfiguration config)
  2. {
  3. config.Routes.MapHttpRoute(
  4. name: "DefaultApi",
  5. routeTemplate: "api/{controller}/{id}",
  6. defaults: new { id = RouteParameter.Optional }
  7. );
  8.  
  9. config.Routes.MapHttpRoute(
  10. name: "DefaultApiGet",
  11. routeTemplate: "api/{controller}/{action}/{regionId}",
  12. defaults: new { action = "Get" },
  13. constraints: new { httpMethod = new HttpMethodConstraint("GET") });
  14.  
  15. var json = config.Formatters.JsonFormatter;
  16. json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
  17. config.Formatters.Remove(config.Formatters.XmlFormatter);
  18.  
  19. namespace CallCOP.Controllers
  20. {
  21. public class DepartmentController : Controller
  22. {
  23. HttpClient client = new HttpClient();
  24. HttpResponseMessage response = new HttpResponseMessage();
  25. Uri contactUri = null;
  26.  
  27. public DepartmentController()
  28. {
  29. // set base address of WebAPI depending on your current environment
  30. client.BaseAddress = new Uri(ConfigurationManager.AppSettings[string.Format("APIEnvBaseAddress-{0}", CallCOP.Helpers.ConfigHelper.COPApplEnv)]);
  31.  
  32. // Add an Accept header for JSON format.
  33. client.DefaultRequestHeaders.Accept.Add(
  34. new MediaTypeWithQualityHeaderValue("application/json"));
  35. }
  36.  
  37. // need to only get departments that correspond to a Contact ID.
  38. // GET: /Department/?regionId={0}
  39. public ActionResult Index(int regionId)
  40. {
  41. response = client.GetAsync(string.Format("api/department/GetDeptsByRegionId/{0}", regionId)).Result;
  42. if (response.IsSuccessStatusCode)
  43. {
  44. var departments = response.Content.ReadAsAsync<IEnumerable<Department>>().Result;
  45. return View(departments);
  46. }
  47. else
  48. {
  49. LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
  50. "Cannot retrieve the list of department records due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
  51. return RedirectToAction("Index");
  52. }
  53.  
  54. }
  55.  
  56. //
  57. // GET: /Department/Create
  58.  
  59. public ActionResult Create(int regionId)
  60. {
  61. return View();
  62. }
  63.  
  64. //
  65. // POST: /Department/Create
  66. [HttpPost]
  67. [ValidateAntiForgeryToken]
  68. public ActionResult Create(int regionId, Department department)
  69. {
  70. department.RegionId = regionId;
  71. response = client.PostAsJsonAsync("api/department", department).Result;
  72. if (response.IsSuccessStatusCode)
  73. {
  74. return RedirectToAction("Edit", "Region", new { id = regionId });
  75. }
  76. else
  77. {
  78. LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
  79. "Cannot create a new department due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
  80. return RedirectToAction("Edit", "Region", new { id = regionId });
  81. }
  82. }
  83.  
  84. //
  85. // GET: /Department/Edit/5
  86.  
  87. public ActionResult Edit(int id = 0)
  88. {
  89. response = client.GetAsync(string.Format("api/department/{0}", id)).Result;
  90. Department department = response.Content.ReadAsAsync<Department>().Result;
  91. if (department == null)
  92. {
  93. return HttpNotFound();
  94. }
  95. return View(department);
  96. }
  97.  
  98. //
  99. // POST: /Department/Edit/5
  100.  
  101. [HttpPost]
  102. [ValidateAntiForgeryToken]
  103. public ActionResult Edit(int regionId, Department department)
  104. {
  105. response = client.GetAsync(string.Format("api/department/{0}", department.Id)).Result;
  106. contactUri = response.RequestMessage.RequestUri;
  107. response = client.PutAsJsonAsync(string.Format(contactUri.PathAndQuery), department).Result;
  108. if (response.IsSuccessStatusCode)
  109. {
  110. return RedirectToAction("Index", new { regionId = regionId });
  111. }
  112. else
  113. {
  114. LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
  115. "Cannot edit the department record due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
  116. return RedirectToAction("Index", new { regionId = regionId });
  117. }
  118. }
  119.  
  120. //
  121. // GET: /Department/Delete/5
  122.  
  123. public ActionResult Delete(int id = 0)
  124. {
  125. response = client.GetAsync(string.Format("api/department/{0}", id)).Result;
  126. Department department = response.Content.ReadAsAsync<Department>().Result;
  127.  
  128. if (department == null)
  129. {
  130. return HttpNotFound();
  131. }
  132. return View(department);
  133. }
  134.  
  135. //
  136. // POST: /Department/Delete/5
  137.  
  138. [HttpPost, ActionName("Delete")]
  139. [ValidateAntiForgeryToken]
  140. public ActionResult DeleteConfirmed(int regionId, int id)
  141. {
  142. response = client.GetAsync(string.Format("api/department/{0}", id)).Result;
  143. contactUri = response.RequestMessage.RequestUri;
  144. response = client.DeleteAsync(contactUri).Result;
  145. return RedirectToAction("Index", new { regionId = regionId });
  146. }
  147. }
  148. }
  149.  
  150. namespace CallCOPAPI.Controllers
  151. {
  152. public class DepartmentController : ApiController
  153. {
  154. private CallCOPEntities db = new CallCOPEntities(HelperClasses.DBHelper.GetConnectionString());
  155.  
  156. // GET api/department
  157. public IEnumerable<Department> Get()
  158. {
  159. return db.Departments.AsEnumerable();
  160. }
  161.  
  162. // GET api/department/5
  163. public Department Get(int id)
  164. {
  165. Department dept = db.Departments.Find(id);
  166. if (dept == null)
  167. {
  168. throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
  169. }
  170.  
  171. return dept;
  172. }
  173.  
  174. // this should accept a contact id and return departments related to the particular contact record
  175. // GET api/department/5
  176. public IEnumerable<Department> GetDeptsByRegionId(int regionId)
  177. {
  178. IEnumerable<Department> depts = (from i in db.Departments
  179. where i.RegionId == regionId
  180. select i);
  181. return depts;
  182. }
  183.  
  184. // POST api/department
  185. public HttpResponseMessage Post(Department department)
  186. {
  187. if (ModelState.IsValid)
  188. {
  189. db.Departments.Add(department);
  190. db.SaveChanges();
  191.  
  192. HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, department);
  193. return response;
  194. }
  195. else
  196. {
  197. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  198. }
  199. }
  200.  
  201. // PUT api/department/5
  202. public HttpResponseMessage Put(int id, Department department)
  203. {
  204. if (!ModelState.IsValid)
  205. {
  206. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  207. }
  208.  
  209. if (id != department.Id)
  210. {
  211. return Request.CreateResponse(HttpStatusCode.BadRequest);
  212. }
  213.  
  214. db.Entry(department).State = EntityState.Modified;
  215.  
  216. try
  217. {
  218. db.SaveChanges();
  219. }
  220. catch (DbUpdateConcurrencyException ex)
  221. {
  222. return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
  223. }
  224.  
  225. return Request.CreateResponse(HttpStatusCode.OK);
  226. }
  227.  
  228. // DELETE api/department/5
  229. public HttpResponseMessage Delete(int id)
  230. {
  231. Department department = db.Departments.Find(id);
  232. if (department == null)
  233. {
  234. return Request.CreateResponse(HttpStatusCode.NotFound);
  235. }
  236.  
  237. db.Departments.Remove(department);
  238.  
  239. try
  240. {
  241. db.SaveChanges();
  242. }
  243. catch (DbUpdateConcurrencyException ex)
  244. {
  245. return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
  246. }
  247.  
  248. return Request.CreateResponse(HttpStatusCode.OK, department);
  249. }
  250. }
  251. }
  252.  
  253. <modules runAllManagedModulesForAllRequests="true">
  254. <remove name="WebDAVModule"/> <!-- add this -->
  255. </modules>
  256.  
  257. <handlers>
  258. <remove name="WebDAV" />
  259. ...
  260. </handlers>
  261.  
  262. <configuation>
  263. <system.webServer>
  264. <handlers>
  265. <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  266. <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  267. <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  268. <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  269. <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  270. <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  271. </handlers>
  272. </system.webServer>
  273. </configuration>
  274.  
  275. PUT http://www.fluff.com/api/Fluff/123 HTTP/1.1
  276. Host: www.fluff.com
  277. Content-Length: 11
  278.  
  279. {"Data":"1"}
  280.  
  281. <system.webServer>
  282. <modules runAllManagedModulesForAllRequests="true">
  283. <remove name="WebDAVModule"/> <!-- add this -->
  284. </modules>
  285. <handlers>
  286. <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  287. <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  288. <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  289. <remove name="WebDAV" />
  290. <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  291. <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  292. <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  293. </handlers>
  294. </system.webServer>
  295.  
  296. public async Task<IHttpActionResult> SetAmountOnEntry(string id, [FromBody]int amount)
  297.  
  298. public async Task<IHttpActionResult> UpdateEntry(string id, MyEntry entry)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement