1

I'm using the microsoft asp.net identity tutorial sample app [Here][1] just until I feel comfortable with the functionality needed for my project. I need to have an API that I can call from a separate MVC web app to do authentication/authorization against a local sql server and pass login credentials from the web app to the api to get the header token etc. Then I need to be able to check the token for any requests to pull data or save data back to the db.

I added a web app project to that example solution that is just a form with a button and some jquery to catch the submit button being clicked:

$(document).ready(function () {

    var register = function() {
        var dataa = {
            Email: "password@host.com",
            Password: "password",
            ConfirmPassword: "password"
        };

        $.ajax({
            type: 'POST',
            url: '/api/Account/Register',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(dataa)
        });
        return false;
    }

    $('#btnRegister').click(register);
});

and then here is the controller on the api itself:

[Authorize]
[EnableCors("*","*","*")]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    [AllowAnonymous]
    [Route("Register")]
    [HttpPost]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }
}

When I try to call the Register function on the api I get a 404 error (jquery-1.10.2.js:8720 POST http://localhost:35714/api/Account/Register 404 (Not Found)) in browser. How can I hit the api function from the front end, and can this call be made from my web app Controller or should it be client side?

Added Microsoft.aspnet.cors and microsoft.aspnet.webapi.cors, added config.EnableCors() to webapiconfig.cs and [EnableCors] to the accountcontroller that inherits from apicontroller.

  • 1
    Replace `'api/Account/Register'` with `'/api/Account/Register'` (prepend a `/` to the url to make it absolute) – haim770 Oct 24 '16 at 17:50
  • I noticed that as well and updated my code to reflect that I already tried that, same error. – Dylan Schmidt Oct 24 '16 at 17:51
  • 1
    Did you make sure your your Url is indeed `/api/Account/Register`? – haim770 Oct 24 '16 at 17:52
  • 1
    Also, try to decorate your `Register` method with `[System.Web.Http.HttpPost]` – haim770 Oct 24 '16 at 17:53
  • Added the HttpPost Data Annotation and now I'm getting a different error: XMLHttpRequest cannot load https://localhost:44305/api/Account/Register. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:35714' is therefore not allowed access. The response had HTTP status code 405. – Dylan Schmidt Oct 24 '16 at 18:02
  • You need to enable CORS then: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api – haim770 Oct 24 '16 at 18:03
  • Enabled CORS, error changed once again: >XMLHttpRequest cannot load https://localhost:44305/api/Account/Register. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:35714' is therefore not allowed access. The response had HTTP status code 500. – Dylan Schmidt Oct 24 '16 at 18:23
  • That's the same error. Update your question with how you enabled CORS. – haim770 Oct 24 '16 at 18:24
  • Updated my question to reflect that I added CORS. Does both projects being on the same solution as I'm testing locally impact this issue because they would be separate when deployed? – Dylan Schmidt Oct 24 '16 at 18:31
  • Just adding the NuGet packages is not enough. Read through the page I linked earlier. At the most basic level, you'll have to call `EnableCors()` on your `HttpConfiguration` (in your `Startup.cs)` – haim770 Oct 24 '16 at 18:42
  • I apologize, I didn't notate that but it was in my code. In WebApiConfig I added config.EnableCors() to the register method, and in my AccountController that inherits from ApiController I added the [EnableCors] annotation. Still getting the 500 error I posted when I run. – Dylan Schmidt Oct 24 '16 at 18:50
  • If preflight options checks are still your problem create a custom message handler. See the answer by MCurbelo [link](http://stackoverflow.com/questions/20792950/net-web-api-cors-preflight-request). Worked for me in my Web API. – Ben Hall Oct 24 '16 at 19:40

2 Answers2

0

You need to add HttpPost attribute to your API method:

[AllowAnonymous]
[Route("Register")]
[System.Web.Http.HttpPost]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
    ...
0

Try this.

$(document).ready(function () {
    var register = function() {
        var dataa = {
            Email: "password@host.com",
            Password: "password",
            ConfirmPassword: "password"
        };

        $.ajax({
            type: 'POST',
            url: '/api/Account/Register',
            contentType: 'application/json; charset=utf-8',
            data: {model: JSON.stringify(dataa)}
        });
        return false;
    }

    $('#btnRegister').click(register);
});
Yashasvi
  • 197
  • 1
  • 3
  • 6