简体   繁体   中英

c# hosted rest service return 404

I've implemented my controller in c#

[ServiceContract(Name = "UserController")]
public interface ApiController
{
    Task<HttpResponseMessage> SignUp(LoginModel model);

    Task<HttpResponseMessage> Login(LoginModel model);


}

namespace Nerder_Backend.Controllers
{
    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
        private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
        private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];

        [Route("signup")]
        [HttpPost]
        public async Task<HttpResponseMessage> SignUp(LoginModel model)
        {
            if (model == null || !model.IsValid())
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Invalid email and/or password")
                };
                return response;
            }

and then I'm trying to host it to be possible to call it via AJAX on jquery, because my app will be mobile cross plaform and I have to separate client side to server side, anyway, that's the hosting main method:

static void Main(string[] args)
        {


            var baseAddress = "http://localhost:8080";
            var config = new HttpSelfHostConfiguration(baseAddress);
            CouchbaseConfig.Register();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            config.MapHttpAttributeRoutes();//map attribute routes
                                            // Create the server
            using (var server = new HttpSelfHostServer(config))
            {
            server.OpenAsync().Wait();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
    }

The host start and it's listening but when I call the URL via javascript i get a 404 error message.

HTTP status code 404.

This is the javascript code:

 $.ajax({
            type: 'post',
            url: 'http://localhost:8080/api/user/signup',

I used also CORS enabler for chrome, how can i check if in any way my path is valid? Should I change the way I host my sevice?

This is my app.config if it can help:

 <system.webServer>
    <!-- ENABLE REST SERVICES -->
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <!--END -->
  </system.webServer>

  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Couchbase.NetClient" publicKeyToken="05e9c6b5a9ec94c2" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.4.5.0" newVersion="2.4.5.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.Core" publicKeyToken="407dd0808d44fbdc" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>

How are you hosting your service?

How are you ensuring the port is actually 8080 when the service is running? - it could be giving 404 error because it is the wrong port

If, for example, your service only exists in Visual Studio and you hit F5 to start debugging and it auto opens a new window for you in your browser, and you see the the "IIS Express" icon in the bottom right taskbar area: the port can vary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM