0

I am trying to create a call from my Angular 4 application to my server that is asp.net web api, first of all I enabled cors in my server and it seems working, now when I am trying to call I am getting method not allowed

WebApi.config:

public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);
    // 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 }
    );
}

Controller method example:

        [HttpGet, Route("api/authentication")]
    public IHttpActionResult Get(string username, string password)
    {
        var s = new ApartmentService();

        if (!s.CheckIfValidLogin(username, password))
        {
            return NotFound();
        }
        return Ok();
    }

client code:

public url = 'http://localhost:50743/api/authentication';

  login(username: string, password: string): Observable<any> {
    let params = new HttpParams();
    params.append('username', username);
    params.append('password', password);
    return this.http.get(this.url, {
      params: params,
      headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'),
    }).map((result: Response) => result.json());
  }

i tried also with header content type: application/json and also didn't worked.

error: error

its working fine if I did the request with postman...

Thanks.

1
  • return this.http.get(this.url,... - the http in there, is it HttpClientModule or HttpModule? Commented Oct 14, 2017 at 14:59

1 Answer 1

0

You are sending a GET request to an endpoint that only accepts POST, that is the reason for the Method Not Allowed error.

Send your request using POST instead. I'm not familiar with angular but try something like

login(username: string, password: string): Observable<any> {
    let params = new HttpParams();
    params.append('username', username);
    params.append('password', password);
    return this.http.post(this.url, parems {
        headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'),
    }).map((result: Response) => result.json());
}

Refer to the angular docs for http.post

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.