I'm a bit desperate with this issue. I'm new on angular 2 and .net and I trying to build a simple application. I programmed an api rest in c#. When i call a GET method from angular it works fine, but not POSTmethod. I receive 405 (Method not allowed) all the time, but if i call the post with postman all works. I see lots of issues with the same problem, but they doesn't work for me.
I have CORS enabled.
Here's my code:
Angular
sendPtipo(delegacion,municipio,ejercicio,recinto,tipo){
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let urlPtipo ='http://localhost:50790/ApiProductoTipo/CalculaPTRecinto';
let body ='delegacion='+delegacion+'&municipio='+municipio+'&recinto='+recinto+'&ejercicio='+ejercicio+'&tipo'+tipo;
return this._http.post(urlPtipo , body , options)
.map(data => {alert('ok');})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}}
Api rest in C#
using System.Collections.Generic;
using System.Web.Http;
using AppName.Models;
using AppName.Service;
using System.Linq;
using AppName.ViewModels;
using System.Net.Http;
using System.Net;
using System.Web.Http.Cors;
namespace Api.Services
{
// Allow CORS for all origins. (Caution!)
//[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ApiProductoTipoController : ApiController
{
private readonly IProductoTipoService productoTipoService;
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
public ApiProductoTipoController(IProductoTipoService productoTipoService)
{
this.productoTipoService = productoTipoService;
}
[HttpPost]
[Route("~/ApiProductoTipo/CalculaPTRecinto")]
public HttpResponseMessage CalculaPTRecinto([FromBody]int delegacion, int municipio, int ninterno, int ejercicio, string tipo)
{
if (this.productoTipoService.CalculaPTRecinto(delegacion, municipio, ninterno, ejercicio, tipo) != 0)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}}
webapiconfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Enable cors
var cors = new EnableCorsAttribute("*", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");
//var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//Configuramos el MapRoute
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ApiWithAction",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
}
}
}
Log
headers:Headers
ok:false
status:405
statusText:"Method Not Allowed"
type:2
url:"http://localhost:50790/ApiProductoTipo/CalculaPTRecinto"
_body:"{"Message":"The requested resource does not support http method 'POST'."}"
Any idea? Thank you for reading!
Edit: this was the response of Postman 200 OK
Cache-Control →no-cache
Content-Length →0
Date →Fri, 26 May 2017 09:48:05 GMT
Expires →-1
Pragma →no-cache
Server →Microsoft-IIS/10.0
X-AspNet-Version →4.0.30319
X-Powered-By →ASP.NET
X-SourceFiles →=?UTF-8?B?QzpcVXNlcnNcNzAyNTU3MjFKXERlc2t0b3BcQXBpUHJvZHVjdG9UaXBvXFdlYlxBcGlQcm9kdWN0b1RpcG9cQ2FsY3VsYVBUUmVjaW50bw==?=
Your code seems ok.Try to change code as I have given below :
Angular
sendPtipo(delegacion: number,municipio: number,ejercicio: number,recinto: number,tipo: string){
let data = new Object();
data.delegacion = delegacion;
data.municipio = municipio;
data.ejercicio = ejercicio;
data.recinto = recinto;
data.tipo = tipo;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let urlPtipo ='http://localhost:50790/ApiProductoTipo/CalculaPTRecinto';
return this._http.post(urlPtipo , data , options)
.map(data => {alert('ok');})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}}
API in C#
using System.Collections.Generic;
using System.Web.Http;
using AppName.Models;
using AppName.Service;
using System.Linq;
using AppName.ViewModels;
using System.Net.Http;
using System.Net;
using System.Web.Http.Cors;
namespace Api.Services
{
// Allow CORS for all origins. (Caution!)
//[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ApiProductoTipoController : ApiController
{
public class myobj{
public int delegacion { get; set; }
public int municipio { get; set; }
public int ejercicio { get; set; }
public int recinto { get; set; }
public string tipo { get; set; }
}
private readonly IProductoTipoService productoTipoService;
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
public ApiProductoTipoController(IProductoTipoService productoTipoService)
{
this.productoTipoService = productoTipoService;
}
[HttpPost]
[Route("~/ApiProductoTipo/CalculaPTRecinto")]
public HttpResponseMessage CalculaPTRecinto(myobj data)
{
var tipo = data.tipo;
...
}
}}
I was facing the same issue.The actual datatype of data you sre sending can't get at API side.That's why its giving 405 error.So try to send data as an object and also receive as an object at API side.
Hope this will help you
Related
I'm following this tutorial https://learn.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
I followed all the steps to the dot, but as soon as I start the program this line
using (WebApp.Start<Startup>(url: baseAddress)) always produce a System.NullReferenceException: 'Object reference not set to an instance of an object.'
Programs.cs
using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
namespace OwinSelfhostSample
{
public class Program
{
static void Main()
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpClient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
}
}
}
Startup.cs
using Owin;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
ValuesController.cs
using System.Collections.Generic;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
I have created API in .Net Framework 4.5 and it's working fine in Postman but When I am implementing with Angular7 then we didn't get Requested Parameters like (Username and Password) in API.
I have already tried these steps:
I have already installed this package
Microsoft.AspNet.WebApi.Cors
DemoController.cs
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
using TestData.Models;
namespace TestData.Controllers
{
public class DemoController : ApiController
{
[HttpPost]
[Route("api/Demo/Login")]
public IHttpActionResult Login(HttpRequestMessage request)
{
string username = HttpContext.Current.Request.Form["Username"]; // getting Null
string pass = HttpContext.Current.Request.Form["Pass"]; // getting Null
return Ok('Username: ' +username + 'Password :' +pass);
}
}
}
WebApiConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace TestData
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
}
}
I am using some code of Angular
auth.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class AuthService {
apiUrl : any = 'http://mydomain/api';
constructor(private http : HttpClient) { }
GetHttpHeaders() : HttpHeaders {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return headers;
}
loginUser() {
var data = JSON.stringify({
"Username" : '3333',
"Pass" : '123456'
})
return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
console.log(results);
});
}
}
In UI you have added 'Content-Type', 'application/json', So it is better if you accept parameter of type object in ActionResult.
Try this Solution:
Backend:
public IHttpActionResult Login(JObject request)
{
string username = Convert.ToString(request.SelectToken("Username"))
...
}
UI:
loginUser(){
var data = {
"Username" : '3333',
"Password" : '123456'
}
return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
console.log(results);
});
}
Another way is to create a Model Class:
public class LoginRequestDTO
{
public string Username{ get; set; }
public string Password{ get; set; }
}
and ActionResult:
public IHttpActionResult Login(LoginRequestDTO request)
{
string username = request.Username;
...
}
(Sorry if my english sucks a little)
I'm trying to call an api method from a mvc controller but the mvc seems unable to find the method. I set the route in the mvc controller as
[Route("[controller]")]
and in the api controller as
[Route("api/[controller]")]
In the startup.cs file i added this command to enable default route
app.UseMvcWithDefaultRoute();
Mvc controller code:
[HttpGet]
public async Task<ActionResult> GetAll()
{
IEnumerable<Utente> utenti = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:57279/");
var Res = await client.GetAsync("api/utente/GetAll");
if (Res.IsSuccessStatusCode)
{
var readTask = Res.Content.ReadAsAsync<IList<Utente>>();
utenti = readTask.Result;
}
else
{
utenti = Enumerable.Empty<Utente>();
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
}
return View(utenti);
}
Api code:
[HttpGet]
public IHttpActionResult GetAll()
{
IList<Utente> utenti = null;
using (_utenteContext)
{
utenti = _utenteContext.Utenti.Select(u => new Utente()
{
id = u.id,
user = u.user,
password = u.password
}).ToList<Utente>();
}
if (utenti.Count == 0)
{
return NotFound();
}
return Ok(utenti);
}
The problem might be that I'm following an old example for both mvc and api controllers in same project, but I'd like if you guys could help me with it.
In the:
var Res = await client.GetAsync("api/utente/GetAll");
I always get {StatusCode: 404, ReasonPhrase: 'Not Found',...} no matter the changes I make to the code.
EDIT:
Whole Api Controller (I was trying also with a POST method but it doesn't work either)
using AdrianWebApi.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace AdrianWebApi.Controllers.api
{
[Route("api/[controller]")]
public class UtenteController : ApiController
{
private readonly UtenteContext _utenteContext;
public UtenteController(UtenteContext context)
{
_utenteContext = context;
}
[HttpGet]
public IHttpActionResult GetAll()
{
IList<Utente> utenti = null;
using (_utenteContext)
{
utenti = _utenteContext.Utenti.Select(u => new Utente()
{
id = u.id,
user = u.user,
password = u.password
}).ToList<Utente>();
}
if (utenti.Count == 0)
{
return NotFound();
}
return Ok(utenti);
}
[HttpPost]
public IHttpActionResult PostNewUtente(Utente utente)
{
if (!ModelState.IsValid)
return BadRequest("Not a valid model");
using (_utenteContext)
{
_utenteContext.Utenti.Add(new Utente()
{
id = utente.id,
user = utente.user,
password = utente.password
});
_utenteContext.SaveChanges();
}
return Ok();
}
}
}
EDIT 2
Startup class if it's useful:
using AdrianWebApi.Models;
using AdrianWebApi.Models.DataManager;
using AdrianWebApi.Models.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace AdrianWebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UtenteContext>(options =>{options.UseMySQL("server=localhost;database=dbutenti;User ID=root;password=root;");});
services.AddScoped<IDataRepository<Utente>, DataManager>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvcWithDefaultRoute();
}
}
}
EDIT 3 Post method MVC if someone is interested, working, at least for me:
[Route("Add")]
[System.Web.Http.HttpPost]
public ActionResult Add([FromForm]Utente utente)
{
if (utente.password == null)
{
return View();
}
else
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:57279/api/");
//HTTP POST
var postTask = client.PostAsJsonAsync<Utente>("utente", utente);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("GetAll");
}
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(utente);
}
}
Try commenting out your controller and replacing it with this code below, then go to api/utente/ and see if you get a result. If you do then replace what you need with your code.
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace AdrianWebApi.Controllers.api
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "Test 1", " Test 2" };
}
}
}
What URI should I enter to run my Web API 2 rating route?
I have tried the following URIs with POST method and I get 404 errors:
http://localhost:52229/PersonalAutoAPI/RunRating
This one works (different controller):
http://localhost:52229/PersonalAutoAPI/Drivers
I can GET my driver API
Here is my webapiconfig.config.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace PersonalAuto
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "PersonalAutoAPI",
routeTemplate: "PersonalAutoAPI/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
}
Here it is my RatingControler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using PersonalAuto.Models;
namespace PersonalAuto.Controllers
{
public class RatingControler : ApiController
{
public IEnumerable<RatingResult> PostRunRaing([FromBody] RatingInfo MyRateInfo)
{
RatingResult[] myRatingResult =
{new RatingResult{PremiumDP = 0M,PremiumEFTDownPament = 0M,PremiumMontlyPayment = 0M,PremiumEFTMonthlyPayment=0M,PremiumPIF=0M }
};
return myRatingResult;
}
public IHttpActionResult PostRunRating([FromBody] RatingInfo MyRateInfo)
{
RatingResult MyRating = new RatingResult { PremiumDP = 0M, PremiumEFTDownPament = 0M, PremiumMontlyPayment = 0M, PremiumEFTMonthlyPayment = 0M, PremiumPIF = 0M };
if (MyRating == null)
{
return NotFound();
}
return Ok(MyRating);
}
}
}
Here it is my diverscontroler.cs (this works with above uri)
using PersonalAuto.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Http;
using System.Linq;
using System.Net.Http;
using System.IO;
namespace PersonalAuto.Controllers
{
public class DriversController : ApiController
{
public IEnumerable<Driver> GetAllDrivers()
{
Driver[] myDriverArray =
{
new Driver { id = "1234", first_name = "eric", last_name = "last", dl_number = "1234", address_1 = "1234 test st", address_2 = "", city = "dallas", state = "TX", zip = "75248", mobile = "214-415-9224" }
};
return myDriverArray;
}
public IHttpActionResult GetDriverByLicenseNo(string drivers_license_number, string drivers_license_state)
{
string PreToken = "xxxxx:xxx:xxxxxxxxxxxxx";
string Token = Convert.ToBase64String(Encoding.UTF8.GetBytes(PreToken));
if (drivers_license_state == null)
drivers_license_state = "TX";
var driver = new Driver { id = Token, first_name = "eric", last_name = "last", dl_number = "1234", address_1 = "1234 test st", address_2 = "", city = "dallas", state = "TX", zip = "75248", mobile = "214-415-9224" }; // products.FirstOrDefault((p) => p.Id == id);
if (driver == null)
{
return NotFound();
}
return Ok(driver);
}
}
}
I have been pulling my hair out over this! Any help would be appreciated!
The routing setup depends on the controller class name ending in Controller. In your sample code, you have it misspelled: RatingControler should be RatingController
Also check the spelling of PostRunRaing - which seems like it should be PostRunRating, (but it can't be because then you would have a naming conflict. The controller wouldn't know whether to return an IEnumerable or an IHttpActionResult.)
Fix that, and then I think your route will be:
http://localhost:52229/PersonalAutoAPI/Rating/PostRunRating
There code has two problem:
Change RatingControler to RatingController. The controller factory doesn't recognize RatingControler because it expects *Controller.
you cannot have two method with same http verb and method name. you can not overload methods in controllers.
I'm making a very simple Web API using MVC.NET to retrieve values from the following database:
CREATE TABLE [dbo].[Rates] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR (3) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Rate] DECIMAL (5, 2) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
For whatever reason that I do not understand, whenever I compile my solution and navigate to localhost:xxxxx/api or api/Rates (my controller), I get the following error:
Server Error in '/' Application
The Resource cannot be found. (A Http 404 error)
I do not understand why this is happening, as it's a freshly built api application, using Entity Framework.
Below are my controllers and WebApiConfig classes. Perhaps something in one of those is amiss?
WebApiConfig:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Net.Http.Headers;
namespace ExchangeService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "localhost:63484/api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
}
}
ValuesController (Left as default)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ExchangeService.Controllers
{
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
And finally, my Rates controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using ExchangeService.Models;
namespace ExchangeService.Controllers
{
public class RatesController : ApiController
{
private ExRatesDBEntities db = new ExRatesDBEntities();
// GET: api/Rates
public IQueryable<Rate> GetRates()
{
return db.Rates;
}
// GET: api/Rates/5
[ResponseType(typeof(Rate))]
public IHttpActionResult GetRate(int id)
{
Rate rate = db.Rates.Find(id);
if (rate == null)
{
return NotFound();
}
return Ok(rate);
}
// PUT: api/Rates/5
[ResponseType(typeof(void))]
public IHttpActionResult PutRate(int id, Rate rate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != rate.Id)
{
return BadRequest();
}
db.Entry(rate).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!RateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Rates
[ResponseType(typeof(Rate))]
public IHttpActionResult PostRate(Rate rate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Rates.Add(rate);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = rate.Id }, rate);
}
// DELETE: api/Rates/5
[ResponseType(typeof(Rate))]
public IHttpActionResult DeleteRate(int id)
{
Rate rate = db.Rates.Find(id);
if (rate == null)
{
return NotFound();
}
db.Rates.Remove(rate);
db.SaveChanges();
return Ok(rate);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool RateExists(int id)
{
return db.Rates.Count(e => e.Id == id) > 0;
}
}
}
The only other point of interest I can think of, is that this application is running from an external hard drive. I can't think of any reason why this should be an issue, but thought it would be worth noting. Thanks.
For whatever reason that I do not understand, whenever I compile my solution and navigate to localhost:xxxxx/api or api/Rates (my controller), I get the following error:
Server Error in '/' Application
The Resource cannot be found. (A Http 404 error)
In the first case it cause, because you didn't specify API controller, in the second case, because you didn't specify method of API controller.
Try to call it as http://localhost:63484/api/Rates/GetRates
UPDATE:
Looks like you haven't registered your routes correctly, since you are using both MVC and Web API, so try these configurations:
WebApiConfig class:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
RouteConfig class:
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
And then call them in your Global.asax class:
protected void Application_Start()
{
...
//next line registers web api routes
GlobalConfiguration.Configure(WebApiConfig.Register);
...
//next line registers mvc routes
RouteConfig.RegisterRoutes(RouteTable.Routes);
...
}
I don't believe you need to list the port.
Change the following in your WebApiConfig:
routeTemplate: "localhost:63484/api/{controller}/{id}"
to
routeTemplate: "api/{controller}/{id}"
Try also renaming:
GetRates() to Get()
and calling:
http://localhost:63484/api/Rates
For a rate with an Id you will need to make the following changes:
// GET: api/Rates/5
[ResponseType(typeof(Rate))]
public IHttpActionResult GetRate(int id)
{
Rate rate = db.Rates.Find(id);
if (rate == null)
{
return NotFound();
}
return Ok(rate);
}
to
// GET: api/Rates/5
[ResponseType(typeof(Rate))]
public IHttpActionResult Get(int id)
{
Rate rate = db.Rates.Find(id);
if (rate == null)
{
return NotFound();
}
return Ok(rate);
}
Actually all your Actions in your RateController need to be renamed. Use the same naming convention as you did in your ValuesController. WepAPI is meant to operate off of the named Actions Get(), Put(), Post() etc.